表A
ID | NAME
-----+-------
n1 | BLACK
n2 | WHITE
n3 | RED
n4 | GREEN
表B
ID | A_ID | BLABLA | TIME
---+---------+---------------+--------
1 | n1 | X | sometime
2 | n1 | X | sometime
3 | n1 | X | sometime
4 | n1 | Y | sometime
5 | n1 | Z | sometime
6 | n2 | Y | sometime
7 | n2 | Y | sometime
8 | n2 | Y | sometime
9 | n3 | X | sometime
10 | n3 | Z | sometime
11 | n3 | Z | sometime
12 | n3 | Z | sometime
我的问题
我想查询show Table Result并仅使用MySQL查询。
表格结果
NAME | X | Y | Z
-----------+----------+---------+-----
BLACK | 3 | 1 | 0
WHITE | 0 | 3 | 0
RED | 1 | 0 | 3
GREEN | 0 | 0 | 0
答案 0 :(得分:1)
SELECT
a.name
, sum(CASE WHEN b.blabla LIKE 'X' THEN 1 ELSE 0 END) AS X
, sum(CASE WHEN b.blabla LIKE 'Y' THEN 1 ELSE 0 END) AS Y
, sum(CASE WHEN b.blabla LIKE 'Z' THEN 1 ELSE 0 END) AS Z
FROM tablea a
INNER JOIN tableb b ON (a.id = b.a_id)
GROUP BY a.name
我使用like
代替=
,因为like
始终不区分大小写且=
不是。{1}}
如果blabla
是枚举,那么我建议使用=
。