开发者

ordering by rows

开发者 https://www.devze.com 2023-02-25 15:19 出处:网络
OK so I have a query I am trying to build.. I have 2 tables, table1 has a b开发者_JAVA技巧unch of regular records as normal with a unique ID (auto increment) and table2 has records that include some o

OK so I have a query I am trying to build.. I have 2 tables, table1 has a b开发者_JAVA技巧unch 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 :)


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消