如何使用OR或JOIN合并消息?

时间:2013-08-10 03:38:11

标签: mysql

我想只显示A人和B人之间的对话。

输入Facebook消息...

问题是我的查询正在返回所有消息,而不仅仅是所选人员之间的消息。

如何使用OR或JOIN解决此问题?

SELECT  * 
FROM    msgs 
WHERE   usr_to = 'myself'
AND     author_msg = 'he' 
OR      author_msg = 'myself' 
AND     usr_to = 'he' 
ORDER BY id DESC 
LIMIT 12

2 个答案:

答案 0 :(得分:1)

使用括号对条件进行分组:

$mysql = mysql_query(
    "SELECT * 
    FROM msgs 
    WHERE
        (usr_to = 'myself' AND author_msg = 'he')
        OR
        (author_msg = 'myself' AND usr_to = 'he') 
    ORDER BY id DESC 
    LIMIT 12",
    $mysql
);

答案 1 :(得分:0)

ANDOR逻辑运算符具有不同的优先级(OR低于AND),因此通常在使用OR和{{AND时1}}你需要用括号分组:

SELECT * FROM msgs
WHERE (usr_to = 'myself' AND author_msg = 'he') OR
      (author_msg = 'myself' AND usr_to = 'he')
ORDER BY id DESC
LIMIT 12

您还可以使用IN并指定一组有效组合;这样可以避免担心AND / OR优先级:

SELECT * FROM msgs
WHERE (usr_to, author_msg) IN (('myself', 'he'), ('he', 'myself))
ORDER BY id DESC
LIMIT 12