1

The query below loads all conversations, however, I wanted to only load the conversation between two people.

SELECT * FROM msg 
WHERE senderid = '{$sender}' 
OR recid = '{$recipient}' 
OR recid = '{$sender}' 
OR senderid = '{$recipient}' 
order by id asc

How would I use the AND & OR operators together? Would the following work?

SELECT * FROM msg 
WHERE senderid = '{$sender}' 
AND recid = '{$recipient}' 
OR recid = '{$sender}' 
AND senderid = '{$recipient}' 
order by id asc
1
  • 2
    Still, be careful with mixing AND and OR in boolean expressions. It is easy to make mistakes. Use parentheses to be safe. Commented Aug 21, 2012 at 14:44

2 Answers 2

4

When using AND and OR together, use parentheses to group your logic and make sure the it does what you expect:

SELECT * FROM msg 
WHERE (senderid = '{$sender}' AND recid = '{$recipient}')
OR    (recid = '{$sender}' AND senderid = '{$recipient}')
order by id asc
Sign up to request clarification or add additional context in comments.

2 Comments

I'd like to add for other people that it's always much better to have too many parentheses (brackets?) than too few!
@jslvtr Agreed! On an additional note, further clarification on used terminology can be found here: en.wikipedia.org/wiki/Bracket :)
0

Please find below.

SELECT * FROM msg 
WHERE (senderid = '{$sender}' AND recid = '{$recipient}') 
OR (recid = '{$sender}' AND senderid = '{$recipient}') 
order by id asc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.