tags:

views:

24

answers:

4

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!

+2  A: 
    SELECT a.*
         , b.cnt
      FROM TableA a
   LEFT OUTER JOIN (SELECT a_id
                         , COUNT(*) cnt
                      FROM TableB b
                   GROUP BY a_id) b
   ON a.id = b.a_id
     ORDER BY b.cnt
dcp
Note: This omits rows from the result if they have no rows in TableB.
Mark Byers
@Mark Byers - Fixed.
dcp
Thanks for all the answers everyone. Thanks dcp, this worked like a charm!
KyleT
A: 

Something like this could do the trick.

select a.id, a.name, a.description, count(b.id) as count 
   from TableA as a 
   inner join TableB as b on a.id = b.a_id 
   group by a.id, a.name, a.description order by count 
jpabluz
Note: This omits rows from the result if they have no rows in TableB.
Mark Byers
A: 

Your query already does what you want. You might want to add DESC if you want the rows with the largest number of rows first:

SELECT * FROM TableA
ORDER BY (SELECT COUNT(*) FROM TableB where TableB.a_id = TableA.id) DESC
Mark Byers
A: 
SELECT a.id, a.name, a.description, count(b.id) FROM TableA a
    JOIN TableB b on b.a_id = a.id
GROUP BY a.id, a.name, a.description ORDER BY COUNT(b.id);

You can add an DESC to the ORDER BY, maybe that is what you need:

SELECT a.id, a.name, a.description, count(b.id) FROM TableA a
    JOIN TableB b on b.a_id = a.id
GROUP BY a.id, a.name, a.description ORDER BY COUNT(b.id) DESC;
Francisco Soto