![](/img/trans.png)
[英]MySQL select Distinct records in 1 table and count each group based on values in another table
[英]Count distinct records from child table for each user in MYSQL
我有一个竞赛,计算每个用户收集了多少种。 这由3个表管理:
+----+---------+ | id | user_id | +----+---------+ | 1 | 1 | | 2 | 10 | | 3 | 1 | | 4 | 3 | | 5 | 1 | | 6 | 10 | +----+---------+
+----+--------+---------+--+
| id | sub_id | spec_id | |
+----+--------+---------+--+
| 1 | 1 | 1000 | |
| 2 | 1 | 1003 | |
| 3 | 1 | 2520 | |
| 4 | 2 | 7600 | |
| 5 | 2 | 1000 | |
| 6 | 3 | 15 | |
+----+--------+---------+--+
+--------+-------+--+
| usename | name |
+---------+-------+--+
| 1 | David |
| 10 | Ruth |
| 3 | Rick |
+--------+-------+--+
我需要列出以降序排列的具有最独特规格的用户。 预期的输出:David共有2个独特的规格,Ruth共有2个独特的规格。
+--------+---------+
| id | total |
+----+-------------+
| David | 2 |
| Ruth | 2 |
| Rick | 2 |
+----+-------------+
到目前为止,我有这个,它产生了一个结果。
但它不准确,它会计算总记录。
我可能在子查询中某处缺少DISTINCT。
SELECT s.id, s.user_id,u.name, sum(t.count) as total FROM sub s LEFT JOIN ( SELECT id, sub_id, count(id) as count FROM sub_items GROUP BY sub_id ) t ON t.sub_id = s.id LEFT JOIN user u ON u.username = s.user_id GROUP BY user_id ORDER BY total DESC
我已经看过这个解决方案,但是它没有考虑到独特的方面
首先,您必须为所有用户获得最高“得分”,例如:
SELECT count(DISTINCT si.id) as total
FROM sub INNER JOIN sub_items si ON sub.id = su.sub_id
GROUP BY sub.user_id
ORDER BY total DESC
LIMIT 1
然后,您可以使用该查询将查询限制为共享最大分数的用户:
SELECT u.name, count(DISTINCT si.id) as total
FROM
user u
INNER JOIN sub ON u.usename = sub.user_id
INNER JOIN sub_items si ON sub.id = su.sub_id
GROUP BY u.name
HAVING total =
(
SELECT count(DISTINCT si.id) as total
FROM sub INNER JOIN sub_items si ON sub.id = su.sub_id
GROUP BY sub.user_id
ORDER BY total DESC
LIMIT 1
)
这对我有用,我必须添加
COUNT(distinct spec_id)
到子查询
SELECT s.id, s.user_id,u.name, sum(t.count) as total
FROM sub s
LEFT JOIN (
SELECT sub_id, COUNT(distinct spec_id) as count FROM sub_items group by sub_id
) t ON t.sub_id = s.id
LEFT JOIN user u ON u.username = s.user_id
GROUP BY user_id
ORDER BY total DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.