我有一张这样的表
| id | name |
----------------------
| A | test a1 |
| A | test a2 |
| A | test a3 |
| B | test b1 |
| B | test b2 |
| A | test a4 |
| C | test c1 |
ID A
的值最多,然后是B
,等等。如何返回按id
关联的名称排序的行。我试过这个但是因为我按id
分组,我丢失了与names
相关联的所有id
。
SELECT id, name, COUNT(name) as name_count
FROM users
GROUP BY id
ORDER BY name_count DESC
答案 0 :(得分:3)
你关闭了。要绕过丢失名称,您需要加入子查询来处理计数:
SELECT u.id, u.name
FROM users u
JOIN (
SELECT id, count(1) cnt
FROM users
GROUP BY id) ss
ON u.id = ss.id
ORDER BY ss.cnt DESC
子查询导致此
+----+-----+
| id | cnt |
+----+-----+
| A | 4 |
| B | 2 |
| C | 1 |
+----+-----+
加入原始表格,我们有这些行:
+------+---------+-------+--------+
| u.id | u.name | ss.id | ss.cnt |
+------+---------+-------+--------+
| A | test a1 | A | 4 |
| A | test a2 | A | 4 |
| A | test a3 | A | 4 |
| B | test b1 | B | 2 |
| B | test b2 | B | 2 |
| A | test a4 | A | 4 |
| C | test c1 | C | 1 |
+------+---------+-------+--------+
因此,我们只想返回u
users表中的列,并按子查询ss.cnt
排序。您可以选择u.*
,但通常更好的做法是在您希望查询返回的列中明确显示。
如果您想在ID群组中对结果进行排序,还可以根据u.name
添加排序:
ORDER BY ss.cnt DESC, u.name
答案 1 :(得分:0)
如果users
表中有一列唯一的列,即使没有子查询也可以解决。例如,如果name
是唯一的,那么它将如下所示:
SELECT u1.id, u1.name, COUNT(*) as name_count
FROM users u1
JOIN users u2 ON u1.id = u2.id
GROUP BY u1.name
ORDER BY name_count DESC