MySQL查询使用AND& OR运营商

时间:2012-08-21 14:39:19

标签: mysql sql

下面的查询会加载所有会话,但是,我只想加载两个人之间的会话。

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

我如何使用AND& amp; OR运营商在一起?以下是否有效?

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

2 个答案:

答案 0 :(得分:4)

同时使用ANDOR时,请使用括号对逻辑进行分组,并确保它符合您的预期:

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

答案 1 :(得分:0)

请在下面找到。

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