需要从表中获取特定行,但查询返回多行
MYSQL
SELECT DISTINCT
id, sender_id, msg, name, profilepic, cur_time, cur_date
FROM `chat`
WHERE
(sender_id = '1' AND receiver_id = '3')
OR
(sender_id = '3' AND receiver_id = '1')
AND
chat.id > '3'
表格样本:
id | sender_id | receiver_id | msg | name | profilepic
1 1 3 hi Jay o.jpg
2 1 3 hey Jay o.jpg
3 3 1 hi Tom o.jpg
4 1 3 Yes Jay o.jpg
我希望查询的第4行是id为“4”,但查询仍然返回其他几行
答案 0 :(得分:1)
OR
的优先级低于AND
,因此请在括号中将OR
表达式括起来:
WHERE (
(sender_id = '1' AND receiver_id = '3')
OR (sender_id = '3' AND receiver_id = '1')
)
and chat.id > '3'
考虑原始WHERE
条款:
WHERE
(sender_id = '1' AND receiver_id = '3')
OR
(sender_id = '3' AND receiver_id = '1')
AND
chat.id > '3'
由于AND
优先于OR
,因此会解释如下:
(sender_id = '1' AND receiver_id = '3')
OR
((sender_id = '3' and receiver_id = '1') AND chat.id > '3')
我的答案中提出的括号将强制同时评估两个OR
表达式,如下所示:
((sender_id = '1' AND receiver_id = '3') OR (sender_id = '3' and receiver_id = '1'))
AND
chat.id > '3'
答案 1 :(得分:0)
试试这个
SELECT DISTINCT id, sender_id, msg, name, profilepic, cur_time, cur_date FROM `chat` WHERE ((
sender_id = '1' AND receiver_id = '3') OR (sender_id = '3' AND receiver_id = '1')) and chat.id > '3'
您的原始查询与
的行匹配sender_id = '1' AND receiver_id = '3'
和有
的行sender_id = '3' AND receiver_id = '1' AND chat.id > '3
答案 2 :(得分:0)
问题是你试图同时评估这两个条款:
(sender_id = '3' AND receiver_id = '1')
AND
chat.id > '3'
永远不会成立,请记住,AND运算符比OR运算符绑定更强
所以只需在你的两个OR周围添加paranthesis,这应该没问题
答案 3 :(得分:0)
您需要做的就是为OR条件操作数添加paranthesis。