为 MYSQL 中的每个用户计算来自 child table 的不同记录

Count distinct records from child table for each user in MYSQL

我有一个比赛,计算每个用户收集了多少物种。 这是由 3 tables:

管理的
  1. a parent table 调用了 "sub" 集合,每个集合都是唯一的,有一个 id 并与一个用户 id 相关联。
    
    +----+---------+
    | id | user_id |
    +----+---------+
    |  1 |       1 |
    |  2 |      10 |
    |  3 |       1 |
    |  4 |       3 |
    |  5 |       1 |
    |  6 |      10 |
    +----+---------+
    </pre>
  2. 名为 "sub_items" 的 child table 包含多个唯一的规格记录,并通过子 ID 与 ID 相关 parent table .(每个子可以有多个规格记录)

+----+--------+---------+--+
| id | sub_id | spec_id |  |
+----+--------+---------+--+
|  1 |      1 |    1000 |  |
|  2 |      1 |    1003 |  |
|  3 |      1 |    2520 |  |
|  4 |      2 |    7600 |  |
|  5 |      2 |    1000 |  |
|  6 |      3 |      15 |  |
+----+--------+---------+--+</pre>

  1. 一个用户 table 关联 user_id

+--------+-------+--+
| usename | name    |
+---------+-------+--+
|      1 | David    |
|     10 | Ruth     |
|      3 | Rick     |
+--------+-------+--+</pre>

我需要按降序列出具有最独特规格的用户。 预期输出: David 共有 2 个独特 specs.Ruth 共有 2 个独特规格。

</p>

<pre><code>+--------+---------+
| id     | total   |
+----+-------------+
|  David |    2    |
|  Ruth  |    2    |
|  Rick  |    2    |
+----+-------------+

到目前为止我有这个,它产生了一个结果。但它不准确,它计算总记录。 我可能在 sub-query.

的某处遗漏了一个 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
 </pre>

我看过 this 解决方案,但它没有考虑独特的方面

您首先必须为所有用户获得最大值 "score":

    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
 </pre>