Frage

So in a facebook like wall we have the entities: WallPost. (id, user_id, message) User. (id, name) Connections. (user1_id, user2_id)

I want with one SQL query to get all the wall posts of a user with id: x (example 5) I tried:

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>

So beside the performance problem that this may create, it's also not working correctly when the user doesn't have any connections. I don't want to use two queries because I don't want to sort the results.

Thank you

War es hilfreich?

Lösung

You only want records from wallPost. I would suggest that you remove Connections table in the from clause and put the logic in subqueries using 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>;

For best performance, you would want two indexes, one on Connections(user2_id, user1_id) and the other on Connections(user1_id, user2_id).

Andere Tipps

Why cant you do this?

    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) 

The LEFT JOIN will take care of users who have no connections.

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 )))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top