按行排序

时间:2011-04-15 14:55:32

标签: select count sql-order-by

好的,所以我有一个查询我正在尝试构建..我有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

谢谢:)

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

试试这个:

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