【问题标题】:How to combine post table and image table using sql left join and union如何使用 sql left join 和 union 组合 post 表和 image 表
【发布时间】:2017-11-13 13:30:23
【问题描述】:

我如何组合 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]

【问题讨论】:

  • 在你的第一个连接中尝试使用左连接而不是内连接
  • @sobhanbagheri 但我想确保用户存在
  • 向我们展示数据库架构、示例数据、当前和预期输出。阅读How-to-Ask 这里是START 了解如何提高问题质量并获得更好答案的好地方。 How to create a Minimal, Complete, and Verifiable exampleTips better SQL Question
  • @PhilipJems 您也可以从用户表开始您的选择查询来实现这一点
  • @sobhanbagheri 请你发布答案,我已经尝试了很多东西。目前,当一篇文章有​​多张图片时,它会在每篇文章中复制一张图片

标签: php sql oracle


【解决方案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"   
;

【讨论】:

  • 我发誓我什至不明白如何使用这个查询
  • 哪部分你不明白?你至少了解第一个查询?
  • 请问sql查询中的This is post without image是干什么用的?
  • 使用LEFT JOIN,您尝试将帖子与图像匹配。如果子查询I 没有该帖子的任何结果imgs 将为空。在这种情况下,CASE 语句以适当的方式处理结果。返回'This is post without image'你应该谷歌CASE expresions
  • This is post without image 是一个示例消息,它可能是另一回事。我也尝试过使用您的答案,但没有用
【解决方案2】:

你正在寻找字符串聚合,即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;

【讨论】:

    【解决方案3】:

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

    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:由于我不知道您的确切数据库架构,因此未测试查询

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2012-12-26
      • 2017-12-07
      • 2014-08-10
      相关资源
      最近更新 更多