我有两张桌子
DB2:
id, db1id, text, count_db1
DB1:
id, text
上面的db2由
创建SELECT *, COUNT(`db1id`) AS count_db1 FROM `db2` GROUP BY `db1id` ORDER BY count_db1 DESC
所以最后一列被添加,整个输出按count_db1降序排序。
db1ids是db1的id。我想
SELECT * FROM db1
按db1中count_db1的值排序。如果在db2中db1的id不是db1id,则应将其添加到列表的末尾(即为count_db1指定值0)。
示例:
db2:
id, db1id, text, count_db1
1,4,hello,5
2,4,hello,5
3,4,ho,5
5,4,yeah,5
6,4,no,5
4,3,no,1
db1:
id, text
3, yeahright
4, whatever
因此在db2中db1id 4发生5次,db1id 3发生1次。因此,对db1的条目进行排序,使得id 4出现在id 3之前。结果应为:
答案 0 :(得分:1)
带LEFT JOIN
的简单COUNT
应该可以随心所欲;
SELECT db1.*
FROM db1
LEFT JOIN db2
ON db1.id=db2.db1id
GROUP BY db1.id, db1.text
ORDER BY COUNT(db2.id) DESC
答案 1 :(得分:0)
我没有测试过这个。但也许它适合你:
SELECT db1.text FROM db1 INNER JOIN `db2` ON db2.db1id = db1.id
GROUP BY `db1id`
ORDER BY (COUNT(`db1id`)) DESC
编辑:因为你想看到"空"记录也应该使用其他海报所指出的LEFT JOIN
。
SELECT db1.text FROM db1 LEFT JOIN `db2` ON db2.db1id = db1.id
GROUP BY db1.id, db1.text
ORDER BY (COUNT(`db1id`)) DESC
答案 2 :(得分:0)
LEFT JOIN
是首选,因为即使db1
上id
不存在,您仍希望db2.db1id
上的记录显示在列表中。
SELECT a.text
FROM db1 a
LEFT JOIN db2 b
ON a.id = b.db1id
GROUP BY a.id, a.text
ORDER BY COUNT(b.db1id) DESC
要进一步了解联接,请访问以下链接: