Nervo Tan
Nervo Tan

Reputation: 51

How to select messages from mysql table

I have two fields in my mysql table from_id and to_id

SELECT * FROM `messages` 
WHERE (`from_id` = $user1_id AND `to_id` = $user2_id) OR 
      (`from_id` = $user2_id AND `to_id` = $user1_id)

but this is kinda weird, is there a way to make a query more royal?

its like I want all the messages that I've send and those who were sent to me

Upvotes: 0

Views: 77

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175706

You could use UNION ALL:

SELECT * 
FROM `messages` 
WHERE `from_id` = $user1_id AND `to_id` = $user2_id
UNION ALL
SELECT *
FROM `messages`
WHERE `from_id` = $user2_id AND `to_id` = $user1_id;

Or:

SELECT * 
FROM messages
WHERE (`from_id`, `to_id`) IN (($user1_id,$user2_id),($user2_id,$user1_id))

Upvotes: 3

Related Questions