如何使用按列分组的其他表中的计数对表中的记录进行排序?

时间:2011-09-09 10:20:16

标签: mysql select

我有两张桌子

1. Class table
2. notification table

类表包含类的所有细节

classid | name
 1        myclass
 2        yourclass
 3        ourclass

并且通知表包含

noty_id | notificationname | class_id
  1         editing               1
  2         insertion             1
  3         answered              2
  4         answered updated      2
  5          deleted              3

上表将产生按classid分组的计数,如下所示

SELECT class_id, COUNT(*) AS classcnts FROM notification GROUP BY class_id

现在我希望类表以从通知表中获得的计数的降序显示,如何组合两个查询以获得结果。

提前致谢

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT cl.classid, cl.name, COUNT(no.notificationname) AS classcnts
FROM class cl LEFT JOIN notification no
ON cl.classid = no.class_id
GROUP BY cl.classid
ORDER BY classcnts DESC