Justin Wilson
Justin Wilson

Reputation: 31

ordering by rows

OK so I have a query I am trying to build.. I have 2 tables, table1 has a bunch of regular records as normal with a unique ID (auto increment) and table2 has records that include some of those ids from table1. I am trying to order by the highest records with that same ID in table1.. Heres what I've got:

SELECT * FROM table1 
WHERE table1.status = 1 
AND (SELECT COUNT(*) FROM table2 WHERE table2.tbl1_id = table1.id) 
ORDER BY table1.id DESC

Thanks :)

Upvotes: 0

Views: 34

Answers (2)

Chandu
Chandu

Reputation: 82893

Try this:

SELECT a.*, b.cnt
  FROM table1 a LEFT JOIN
    (
        SELECT tbl1_id, COUNT(*) cnt
            FROM table2
        GROUP BY tbl1_id
    ) b
 ON a.id = b.tbl1_id  
WHERE table1.status = 1 
ORDER BY cnt DESC

Upvotes: 1

Martin Smith
Martin Smith

Reputation: 452977

SELECT table1.id 
FROM table1 
LEFT JOIN table2 ON table2.tbl1_id = table1.id
WHERE table1.status = 1 
GROUP BY table1.id
ORDER BY COUNT(table2.tbl1_id) DESC

Upvotes: 1

Related Questions