加入左边的4个表,或者联盟所有的Sql

时间:2018-02-27 16:49:27

标签: sql join left-join union

这个问题有点复杂,因为在一个SQL查询中混合了4个表。我已经开发了查询但它仍然返回不同于预期的行数。

用户

id_user  |   name
  1           A
  2           B
  3           C
  4           D
  5           E

社区

 id_following  |    id_follower | id_followed
    1                   3               4
    2                   3               5

共享

  id_share | id_post_shared | id_sharer | id_user_post
     1              7           5           1
     2              8           4           2
     3              9           5           4

帖子

    id_post | id_user_post | post
     1              4           Hi
     2              5           Hello
     3              2           Hey you
     4              3           come on
     5              4           here is good
     6              5           go home 
     7              1           lets go home
     8              2           go away
     9              4           come here
    10              1           show

我想检索我关注的用户帖子(用户3)以及我跟随的其他人与其他人共享的帖子(如转发)。

所以从表中我可以期待这个输出(8个结果)

  1             4           Hi
  2             5           Hello
  5             4           here is good
  6             5           go home 
  7             1           lets go home (shared by 5)
  8             2           go away (shared by 4)
  9             4           come here (shared by 5)
  9             4           come here

(意识到#9重复,因为是我关注的人的帖子,同时被用户5共享或转发)

这是我的代码,但经过多次测试,我不确定我想要的是否遵循这种模式

SELECT 
    u.name AS n, p.post AS t
FROM  
    users AS u
LEFT JOIN  
    community AS c ON u.id_user = c.id_followed
LEFT JOIN 
    sharing AS r ON r.id_sharer = c.id_followed
LEFT JOIN 
    posts AS p ON p.id_user = c.id_followed OR p.id_user = r.id_sharer
WHERE 
    c.id_follower = 3  
    AND p.id_user != 3

1 个答案:

答案 0 :(得分:0)

好的,这个版本给你发了两次邮件:

DECLARE 
    @userIcareabout AS TINYINT
SET 
    @userIcareabout = 3 
SELECT
    p.id_post,
    p.id_user_post,
    p.post
FROM
    Posts AS p
WHERE
    p.id_post IN 
    (
    SELECT
        id_post AS post
    FROM
        Posts
    WHERE
        id_user_post IN 
        (
        SELECT 
            id_followed 
        FROM 
            Community
        WHERE
            id_follower = @userIcareabout
        )
    )
UNION ALL   
SELECT
    p.id_post,
    p.id_user_post,
    p.post
FROM
    Posts AS p
WHERE
    p.id_post IN    
    (
    SELECT  
        id_post_shared AS post,
        id_sharer AS poster
    FROM
        Sharing 
    WHERE
        id_user_post IN 
        (
        SELECT 
            id_followed 
        FROM 
            Community
        WHERE
            id_follower = @userIcareabout
        )
    )