用户表
id_name |name
1 |lubo
2 |jano
3 |elena
这里是用户/得分表
id_score |id_name |score |month
1 |1 |0 |1
2 |2 |9 |1
3 |3 |0 |1
4 |1 |2 |2
5 |2 |5 |2
6 |3 |0 |2
7 |1 |0 |3
8 |2 |6 |3
9 |3 |0 |3
我希望得分为0的月份名称列表。 列表应该是这样的。
name |months
lubo |1,3
jano |
elena |1,2,3
我能这样做吗?我有大约1000行。
答案 0 :(得分:3)
重要的步骤是:
试试这个:
SELECT
table1.name,
GROUP_CONCAT(CONVERT(month, CHAR(8)) ORDER BY month) AS months
FROM table2
JOIN table1 ON table2.id_name = table1.id_name
WHERE score = 0
GROUP BY table2.id_name
请注意,GROUP_CONCAT的许多用法都是设计错误。通常最好每个单元格返回一个值。
更新:要获取所有名称,请使用OUTER JOIN:
SELECT
table1.name,
GROUP_CONCAT(CONVERT(month, CHAR(8)) ORDER BY month) AS months
FROM table1
LEFT JOIN table2 ON table2.id_name = table1.id_name AND score = 0
GROUP BY table2.id_name
答案 1 :(得分:2)
SELECT N.name, S.month
FROM scores S
JOIN names N
ON S.id_name = N.id_name
WHERE S.score = 0
然后在您的代码中,您可以根据需要按名称组合月份。
答案 2 :(得分:0)
使用group_concat()之类的
SELECT name ,
GROUP_CONCAT(DISTINCT month ORDER BY month SEPARATOR ",") AS months
FROM users u LEFT JOIN scores s ON u.id_name = s.id_name
WHERE score = 0
GROUP BY name;