SQL:获取朋友发布的帖子

时间:2015-06-24 21:04:56

标签: sql join

我想写一个查询来检索我在应用上的朋友写的所有帖子。

我的表结构是:

Entity:
---------------------
EntityID  -  PK
FirstName -  VARCHAR
LastName  -  VARCHAR

Friends:
---------------------
FriendID  - PK
Friend1   - INT
Friend2   - INT

Post:
---------------------
PostID    - PK
EntityId  - INT
Message   - VARCHAR

上面的模式已经过简化,以演示结构。

到目前为止,我已尝试过以下操作,但它只会检索ID为5的用户发布的帖子。如何让查询返回此用户及其所有朋友的帖子?

SELECT 
   P.PostID,
   P.Message,
   E.FirstName,
   E.LastName,
FROM 
   Entity AS E
JOIN 
   Friends AS F
      ON (E.EntityId = F.Friend1 OR E.EntityId = F.Friend2)
INNER JOIN
   Posts AS P
      ON P.EntityId = F.Friend1 OR P.Entity_Id = F.Friend2
WHERE 
   E.EntityId = 5
ORDER BY
   P.PostID DESC

如果我有数据集:

FriendId   |   Friend1   |   Friend2  |
    1             8             5
    2             9             5
    3             5             3
    4             2             4


PostId     |  EntityId  |  Message
    1             5           Hello
    2             8           Goodbye
    3             2           Morning

我希望只返回hellogoodbye,因为2的用户ID与5没有关联,但应返回所有5个帖子。我一直在盯着这一段时间,似乎无法理解它。

2 个答案:

答案 0 :(得分:3)

基本上,您只需要一个简单的查询即可获得符合条件的帖子:

select * from post
where entityid in (select friend1 from friends where friend2 = 5 )
or entityid in (select friend2 from friends where friend1 =5)
or entityid = 5;

然后添加你需要的东西:

select p.postid, e.lastname,e.firstname,e.entityid , p.message from post p
join entity e on e.entityid=p.entityid    
where p.entityid in (select friend1 from friends where friend2 = 5 )
or p.entityid in (select friend2 from friends where friend1 =5)
or p.entityid = 5;

现在将其更改为加入版本:

select p.postid, e.lastname,e.firstname,e.entityid , p.message from post p
join (
    select friend1 from friends where friend2 =5 
    union select friend2 from friends where friend1 =5 
    union select 5 from dual) m
on p.entityid = m.friend1 
join entity e 
on p.entityid=e.entityid;

答案 1 :(得分:1)

SELECT 
  p.postid
  ,p.message
  ,e.firstname
  ,e.lastname
FROM posts p
  INNER JOIN entity e
  ON e.entityid = p.entityid
WHERE e.entityid IN (
  SELECT friend2
  FROM friends 
  WHERE friend1 = 5

  UNION 

  SELECT friend1 
  FROM friends 
  WHERE friend2 = 5    
)

返回:

postid    message    firstname    lastname
2         Goodbye    John8        Doe8

帖子"你好"由于作者不是用户5的朋友,而是用户5本人,因此不会返回。

SQL Fiddle

相关问题