MySQL根据来自不同表的条件计数

时间:2016-10-04 11:46:49

标签: mysql join count

我有以下表格。


Table : types
--------------------
id | type
--------------------
1  | AA
--------------------
2  | BB
--------------------
3  | AA
--------------------
4  | BB
--------------------    


Table : users
--------------------
id | username
--------------------
1  | abc
--------------------
2  | bcd
--------------------
3  | cde
--------------------
4  | def
--------------------                    


Table : methods
---------------------------------
id | user_id | details  | type_id
---------------------------------
1  |  1      | detail_1 | 1
---------------------------------
2  |  1      | detail_2 | 3
---------------------------------
3  |  1      | detail_3 | 1
---------------------------------
4  |  1      | detail_4 | 3
---------------------------------
5  |  2      | detail_3 | 1
---------------------------------
6  |  2      | detail_5 | 2
---------------------------------
7  |  2      | detail_6 | 4
---------------------------------
8  |  2      | detail_2 | 3
---------------------------------
9  |  1      | detail_2 | 3
---------------------------------
10 |  1      | detail_2 | 3
---------------------------------


Desired Result : 
---------------------------------------------------
UserName | No_of_AA_details | No_of_BB_details |
---------------------------------------------------
abc      | 4                | 0                |
---------------------------------------------------
bcd      | 2                | 2                |
---------------------------------------------------

我需要根据distinct details表中的类型获取types的计数。

我已尝试过这些查询,但我得到的最多是所有计数,而不是不同的值。

SELECT u.username,
CASE WHEN t.type = 'AA' THEN count(distinct m.details) END AS No_of_AA_details,
CASE WHEN t.type = 'BB' THEN count(distinct m.details) END AS No_of_BB_details
FROM users as u inner join methods as m on u.id = m.user_id inner join types as t on t.id = m.type_id 
GROUP BY m.user_id


SELECT u.username,
SUM(t.type = 'AA') AS No_of_AA_details,
SUM(t.type = 'AA') AS No_of_BB_details
FROM users as u inner join methods as m on u.id = m.user_id inner join types as t on t.id = m.type_id 
GROUP BY m.user_id

欢迎任何建议。

1 个答案:

答案 0 :(得分:0)

我无法测试它,但我觉得你有个好主意,可以尝试一下:

SELECT u.username,
  m.user_id,
  CASE
    WHEN t.type = 'AA' THEN 1
    ELSE 0
  END AS No_of_AA_details,
  CASE
    WHEN t.type = 'BB' THEN 1
    ELSE 0
  END AS No_of_BB_details
FROM users as u
INNER JOIN methods as m on u.id = m.user_id
INNER JOIN types as t on t.id = m.type_id

现在你只需要做总和:

SELECT u.username,
      m.user_id,
      SUM (CASE
        WHEN t.type = 'AA' THEN 1
        ELSE 0
      END ) AS No_of_AA_details,
      SUM (CASE
        WHEN t.type = 'BB' THEN 1
        ELSE 0
      END ) AS No_of_BB_details
    FROM users as u
    INNER JOIN methods as m on u.id = m.user_id
    INNER JOIN types as t on t.id = m.type_id
    GROUP BY u.username, m.user_id