【问题标题】:MySQL query- join and concatenate when condition, else nullMySQL查询-条件时连接和连接,否则为空
【发布时间】:2021-10-17 20:07:37
【问题描述】:

我有一张食谱表和一张图片表。

食谱:

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 加入食谱并像这样连接网址:

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;

【问题讨论】:

标签: mysql left-join group-concat


【解决方案1】:

您的联接甚至没有 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

【讨论】:

  • 美丽。我有相同的 on 子句,但 left join 成功了。
  • @MosheM 您也可以通过伪聚合添加标题列。见dbfiddle.uk/…
猜你喜欢
  • 2011-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 2016-11-01
  • 2010-11-06
相关资源
最近更新 更多