我想只显示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
答案 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)
AND
和OR
逻辑运算符具有不同的优先级(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