How to add GROUP_CONCAT to LEFT JOIN query?

*爱你&永不变心* 提交于 2020-01-17 09:13:16

问题


I have this query (and results):

select articles.article_id, articles.article_text, article_photos.photo_filename
from
  articles
left join article_photos
on article_photos.article_id=articles.article_id

>>> results
1,some_text,photo1.jpg
1,some_text,photo2.jpg
1,some_text,photo3.jpg

How do I incorporate GROUP_CONCAT to this so that I get:

>>> results

1,some_text,photo1.jpg
NULL,NULL,photo2.jpg
NULL,NULL,photo3.jpg

Basically, I have a table with articles, and related table with images. An article can have multiple images belonging to it, so I'm trying to print it on screen within while loop, and don't want text to repeat over and over when there's multiple images.


回答1:


select articles.article_id, articles.article_text, group_concat(article_photos.photo_filename)
    from articles
        left join article_photos
            on article_photos.article_id=articles.article_id
    group by articles.article_id, articles.article_text

would return

1    some_text    photo1.jpg,photo2.jpg,photo3.jpg

which is not quite what you've shown in your expected results. Is this what you're asking for?



来源:https://stackoverflow.com/questions/4740598/how-to-add-group-concat-to-left-join-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!