GROUP_CONCAT 在 LEFT JOIN 上生成针对 NULL 的组
GROUP_CONCAT on LEFT JOIN generates groups against NULL
我正在尝试将 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 的问题。
看来您的 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 |
我正在尝试将 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 的问题。
看来您的 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 |