如何使用sql left join和union组合post表和image表

时间:2017-11-13 13:30:23

标签: php sql oracle

如何合并3个表格user tablepost tableimage 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]

3 个答案:

答案 0 :(得分:1)

首先聚合图像:

SELECT 
    imgpostid,
    LISTAGG(url, ', ') WITHIN GROUP (ORDER BY url) "imgs"
FROM Images
GROUP BY imgpostid 

然后添加用户

SQL DEMO

WITH i as (
  SELECT "imgpostid",
          LISTAGG("url", ', ') WITHIN GROUP (ORDER BY "url") "imgs"
  FROM Images
  GROUP BY "imgpostid"
)  
SELECT p."message", i."imgs" as images
FROM post p
LEFT JOIN users u
   ON p."postuserid" = u."userid"
LEFT JOIN i
   ON p."postid" = i."imgpostid"   
;

答案 1 :(得分:0)

您正在寻找字符串聚合,即LISTAGG

select p.*, i.images
from posts p
left join
(
  select imgpostid, listagg(url, ',') within group (order by url) as images
  from images
  group by imgpostid
) i on i.imgpostid = p.postid;

答案 2 :(得分:0)

试试这个,看它是否有效:

SELECT * FROM users
LEFT JOIN posts 
ON users.userid = posts.postuserid
LEFT JOIN images
ON posts.postid = images.imgpostid
WHERE users.pagename = 'a1'
AND users.userid = 801

P.S:由于我不知道您的确切数据库架构

,因此未对测试进行测试