0

我只想显示 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
4

2 回答 2

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
);
于 2013-08-10T03:52:34.017 回答
0

ANDOR逻辑运算符具有不同的优先级(低于ORAND,因此通常在使用ORandAND时需要用括号将它们分组:

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
于 2013-08-10T03:52:36.967 回答