LEFT JOIN上的GROUP_CONCAT根据NULL生成组

时间:2016-03-29 22:19:56

标签: mysql join group-concat

我尝试将LEFT JOIN与GROUP_CONCAT结合使用但未获得预期结果。

两个简单的表格:

weather_alerts:

id | user_id | resort_id
1  | 1       | 1
2  | 1       | 2
3  | 1       | 3
4  | 1       | 5

weather_users

id | email
1  | me@me.com

查询:

SELECT GROUP_CONCAT(wa.resort_id) AS resort_ids, wu.email FROM weather_alerts wa LEFT JOIN weather_users wu ON wa.id = wu.user_id GROUP BY wu.email

而不是生成:

email            resort_ids
me@me.com        1,2,3,5

我明白了:

email            resort_ids
NULL             2,3,5
me@me.com        1

我怀疑这是JOIN而不是CONCAT的问题。

1 个答案:

答案 0 :(得分:2)

您的LEFT JOIN似乎需要改进。

create table weather_alerts (id int, user_id int, resort_id int);
insert into weather_alerts values (1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 1, 5);

create table weather_users (id int, email varchar(100));
insert into weather_users values (1, 'me@me.com');

查询

SELECT GROUP_CONCAT(wa.resort_id ORDER BY wa.resort_id) AS resort_ids, wu.email 
FROM weather_alerts wa 
LEFT JOIN weather_users wu ON wa.user_id = wu.id 
GROUP BY wu.email

请注意,您正在加入wa.id = wu.user_id。联接应该在wa.user_id = wu.id

结果

| resort_ids |     email |
|------------|-----------|
|    1,2,3,5 | me@me.com |