Mysql: Order Results by number of matching rows in Second Table.

Posted by KyleT on Stack Overflow See other posts from Stack Overflow or by KyleT
Published on 2010-05-19T20:59:22Z Indexed on 2010/05/19 21:10 UTC
Read the original article Hit count: 149

Filed under:

I'm not sure the best way to word this question so bear with me.

Table A has following columns:

  • id
  • name
  • description

Table B has the following columns:

  • id
  • a_id(foreign key to Table A)
  • ip_address
  • date

Basically Table B contains a row for each time a user views a row from Table A.

My question is how do I sort Table A results, based on the number of matching rows in Table B.

i.e

SELECT * 
  FROM TableA 
ORDER BY (SELECT COUNT(*) 
            FROM TableB 
           where TableB.a_id = TableA.id)

Thank you!

© Stack Overflow or respective owner

Related posts about mysql