按行排序

| 好的,所以我有一个要构建的查询。我有2个表,table1具有一堆常规记录,这些记录具有正常的唯一ID(自动递增),而table2的记录包含了来自table1的某些ID。我正在尝试按表1中具有相同ID的最高记录进行排序。这就是我所拥有的:
SELECT * FROM table1 
WHERE table1.status = 1 
AND (SELECT COUNT(*) FROM table2 WHERE table2.tbl1_id = table1.id) 
ORDER BY table1.id DESC
谢谢 :)     
已邀请:
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
    
尝试这个:
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
    

要回复问题请先登录注册