在MYSQL中为每个用户计数子表中的不同记录

时间:2018-09-26 15:13:48

标签: mysql distinct

我有一个竞赛,该竞赛计算每个用户收集了多少物种。 这由3个表格管理:

  1. 一个带有集合的名为“ sub”的父表,每个集合都是唯一的,具有一个ID并与一个用户ID相关联。
    
    +----+---------+
    | id | user_id |
    +----+---------+
    |  1 |       1 |
    |  2 |      10 |
    |  3 |       1 |
    |  4 |       3 |
    |  5 |       1 |
    |  6 |      10 |
    +----+---------+
    
  2. 称为“ sub_items”的子表包含多个规范的唯一记录,并通过sub id到id与父表相关。(每个sub可以具有多个规范记录)

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

  1. 具有关联的user_id的用户表

+--------+-------+--+
| usename | name    |
+---------+-------+--+
|      1 | David    |
|     10 | Ruth     |
|      3 | Rick     |
+--------+-------+--+

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

+--------+---------+
| id     | total   |
+----+-------------+
|  David |    2    |
|  Ruth  |    2    |
|  Rick  |    2    |
+----+-------------+

到目前为止,我有这个,它产生了一个结果。但它不准确,它会计算总记录。 我可能在子查询中某处缺少DISTINCT。

+--------+---------+
| id     | total   |
+----+-------------+
|  David |    2    |
|  Ruth  |    2    |
|  Rick  |    2    |
+----+-------------+

我已经研究了this解决方案,但没有考虑到独特之处

2 个答案:

答案 0 :(得分:1)

首先,您必须为所有用户获得最高“得分”:

    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
    )

答案 1 :(得分:0)

这对我有用,我必须添加

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