【发布时间】:2018-05-07 09:08:32
【问题描述】:
我正在尝试运行 sql 查询,该查询可以返回所有用户帖子,如果用户在提交帖子时附加了图片,还可以加入帖子图片。但是使用下面的代码,当post id 存在于post image id 表上时,它只会返回来自post table 的数据,否则它将忽略所有没有图像的帖子。我如何编写一个查询返回有图像和没有图像的帖子?
下面是我的表结构
表 vendor_account
eu_vendor_id | uname | mypagename
-------------|-------|--------------
v801 | peter | pageA
v900 | john |
表 social_posts
social_page_id | post_id | vendor_owner_id | post_body_message
----------------|----------|-----------------|------------------------------
pageA | p100 | v801 | This is post without image
pageA | p101 | v801 | This is post with 2 images
pageA | p102 | v801 | This is post with 1 image
表格 social_post_photos
img | post_image_id | photo_url
----|---------------|---------------
1 | p101 | image1.png
2 | p101 | image2.png
3 | p102 | image01.png
我的 SQL 查询
SELECT
im.post_image_id, p.post_body_message,
group_concat(im.photo_url ORDER BY im.photo_url) imgs
FROM social_post_photos im
LEFT JOIN social_posts p
ON p.post_id = im.post_image_id
INNER JOIN vendor_account v
ON p.vendor_owner_id = v.eu_vendor_id
WHERE p.social_page_id = 'pageA'
AND p.vendor_owner_id = 'v801'
GROUP BY im.post_image_id
当前结果 当我运行上面的 sql 查询时,它会返回如下结果并忽略其他没有附加图像的帖子
post_image_id | post_body_message | photo_url
---------------|----------------------------|-------------------------
p101 | This is post with 2 images | [IMAGE1.PNG],[IMAGE2.PNG]
p102 | This is post with 1 image | [IMAGE01.PNG]
我的预期结果
我想要一个可以返回所有数据的查询,即使它没有图像,因为我使用了LEFT JOIN,因为不是强制帖子附有照片
post_image_id | post_body_message | photo_url
---------------|----------------------------|-------------------------
p101 | This is post with 2 images | [IMAGE1.PNG],[IMAGE2.PNG]
p102 | This is post with 1 image | [IMAGE01.PNG]
p100 | This is post without image | null
【问题讨论】:
标签: mysql sql phpmyadmin group-concat