MySQL query- join and concatenate when condition,否则为空
MySQL query- join and concatenate when condition, else null
我有 table 食谱和 table 图片。
食谱:
id
title
1
'Pancake'
2
'Pudding'
3
'Pizza'
图片:
id
recipe_id
url
1
1
'images\pancake1'
2
1
'images\pancake2'
3
2
'images\pizza
我想加入食谱 images.url 并连接 urls:
recipe_id
urls
1
'images\pancake1, images\pancake2'
2
'images\pizza'
3
null
但我得到:
recipe_id
urls
1
null
2
'images\pancake1, images\pancake2, images\pizza'
3
null
我的查询是:
SELECT r.*,
CASE WHEN i.recipe_id = r.id THEN
GROUP_CONCAT(i.url)
END AS url
FROM recipes r
JOIN images i
GROUP BY r.id;
您的连接甚至没有 ON
子句。
您需要 LEFT
加入:
SELECT r.id recipe_id,
GROUP_CONCAT(i.url ORDER BY i.id) urls
FROM Recipes r LEFT JOIN Images i
ON i.recipe_id = r.id
GROUP BY r.id
我有 table 食谱和 table 图片。
食谱:
id | title |
---|---|
1 | 'Pancake' |
2 | 'Pudding' |
3 | 'Pizza' |
图片:
id | recipe_id | url |
---|---|---|
1 | 1 | 'images\pancake1' |
2 | 1 | 'images\pancake2' |
3 | 2 | 'images\pizza |
我想加入食谱 images.url 并连接 urls:
recipe_id | urls |
---|---|
1 | 'images\pancake1, images\pancake2' |
2 | 'images\pizza' |
3 | null |
但我得到:
recipe_id | urls |
---|---|
1 | null |
2 | 'images\pancake1, images\pancake2, images\pizza' |
3 | null |
我的查询是:
SELECT r.*,
CASE WHEN i.recipe_id = r.id THEN
GROUP_CONCAT(i.url)
END AS url
FROM recipes r
JOIN images i
GROUP BY r.id;
您的连接甚至没有 ON
子句。
您需要 LEFT
加入:
SELECT r.id recipe_id,
GROUP_CONCAT(i.url ORDER BY i.id) urls
FROM Recipes r LEFT JOIN Images i
ON i.recipe_id = r.id
GROUP BY r.id