有没有办法用3个实体改进这个SQL查询?

时间:2014-05-11 01:51:44

标签: sql join

所以在facebook这样的墙上我们有实体: 海报。 (id,user_id,message) 用户。 (id,name) 连接。 (user1_id,user2_id)

我想用一个SQL查询来获取id为x的用户的所有墙帖(示例5) 我试过了:

select wallPost.* from 
wallPost, Connections
Where 
wallPost.user_id = x
or 
(Connections.user1_id =x and wallPost.user_id = connections.user2_id) 
or  
(Connections.user2_id =x and wallPost.user_id = connections.user1_id) 
ORDER BY <field_name>

除了可能产生的性能问题之外,当用户没有任何连接时,它也无法正常工作。我不想使用两个查询,因为我不想对结果进行排序。

谢谢

3 个答案:

答案 0 :(得分:1)

您只需要wallPost的记录。我建议您删除Connections子句中的from表,并使用exists将逻辑放在子查询中:

select wp.*
from wallPost wp 
where wp.user_id = x or 
      exists (select 1 from Connections c where c.user1_id = x and wp.user_id = c.user2_id) or
      exists (select 1 from Connections c where c.user2_id = x and wp.user_id = c.user1_id)
order by <field_name>;

为了获得最佳效果,您需要两个索引,一个在Connections(user2_id, user1_id)上,另一个在Connections(user1_id, user2_id)上。

答案 1 :(得分:0)

select wp.*
from wallPost wp 
where 
wp.user_id = x 
or 
(wp.user_id in
      (select c.user2_id from connections c where c.user1_id = x ) 
)
or
(wp.user_id in (
      (select c.user1_id from connections c where c.user2_id = x )))

答案 2 :(得分:0)

为什么你不能这样做?

    SELECT WP.* FROM [WallPost] WP WITH (NOLOCK)  
       LEFT JOIN [Connections] CN WITH (NOLOCK) 
          ON ((WP.[User_Id] = CN.[User1_Id]) OR (WP.[User_Id] = CN.[User2_Id))
    WHERE (WP.[User_Id] = X) 

LEFT JOIN将照顾没有联系的用户。