【发布时间】:2017-11-13 13:30:23
【问题描述】:
我如何组合 3 个表格 user table、post table 和 image table 以显示带有图像的帖子和不带图像的帖子
使用 sql 内连接、左连接和联合。
表用户
userid | uname | pagename
-------|-------|-----
801 | peter | a1
2 | john |
桌柱
postid | postuserid | message
-------|------------|--------------
10 | 801 | This is post without image
101 | 801 | This is post with 2 images
102 | 801 | This is post with 1 image
表格图片
img | imgpostid | url
----|-----------|------------
1 | 101 | image1.png
2 | 101 | image2.png
3 | 102 | image01.png
我的 SQL 查询
SELECT * FROM Post pt
INNER JOIN Users us
ON pt.postuserid = us.userid
LEFT JOIN Images im
ON pt.postid = im.imgpostid
WHERE us.pagename = 'a1'
AND us.userid = 801
预期结果
This is post without image
This is post with 2 images [IMAGE1.PNG],[IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]
我得到的结果
This is post without image
This is post with 2 images [IMAGE2.PNG]
This is post with 2 images [IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]
【问题讨论】:
-
在你的第一个连接中尝试使用左连接而不是内连接
-
@sobhanbagheri 但我想确保用户存在
-
向我们展示数据库架构、示例数据、当前和预期输出。阅读How-to-Ask 这里是START 了解如何提高问题质量并获得更好答案的好地方。 How to create a Minimal, Complete, and Verifiable exampleTips better SQL Question
-
@PhilipJems 您也可以从用户表开始您的选择查询来实现这一点
-
@sobhanbagheri 请你发布答案,我已经尝试了很多东西。目前,当一篇文章有多张图片时,它会在每篇文章中复制一张图片