使用AND OR在mysql查询中获取正确的行

时间:2013-05-03 13:32:57

标签: mysql

需要从表中获取特定行,但查询返回多行

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”,但查询仍然返回其他几行

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。

SQL FIDDLE DEMO