0

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

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

4 回答 4

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'
于 2013-05-03T13:38:32.077 回答
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
于 2013-05-03T13:38:03.347 回答
0

问题是您尝试同时评估这两个子句:

(sender_id = '3' AND receiver_id = '1')
AND
chat.id > '3'

这永远不会是真的,请记住 AND 运算符的绑定比 OR 运算符强

所以只需在你的两个 OR 周围添加括号就可以了

于 2013-05-03T13:40:29.350 回答
0

您需要做的就是为 OR 条件操作数添加括号。

SQL 小提琴演示

于 2013-05-03T13:57:14.063 回答