查询不返回正确的行

时间:2014-01-14 21:39:46

标签: sql

此查询返回is_message ='on'和mass_message ='on'

的行
SELECT * 
FROM `messages` 
WHERE 
  (`sender_id` = '111' AND `recipient_id` = '222')
  OR (`sender_id` = '222' AND `recipient_id` = '111')
  AND (`is_message` != 'on' OR `is_message` IS NULL)
  AND (`mass_message` != 'on' OR `mass_message` IS NULL)
  AND `invite_for_lunch` = 'on'
LIMIT 0 , 30

如何确保它只返回在{

invite_for_lunch ='的行

这最初是一个计数,但我想查看返回的行。

我检查了列,而is_messagemass_messageinvite_for_lunch)中的两列没有on在同一行。

预期结果:应返回5行

3 个答案:

答案 0 :(得分:2)

尝试修复括号

SELECT * 
FROM `messages` 
WHERE 
 (  
        (`sender_id` = '111' AND `recipient_id` = '222')
     OR (`sender_id` = '222' AND `recipient_id` = '111') 
  )
  AND (`is_message` != 'on' OR `is_message` IS NULL)
  AND (`mass_message` != 'on' OR `mass_message` IS NULL)
  AND `invite_for_lunch` = 'on'
LIMIT 0 , 30

如果没有额外的括号,第一个OR最有可能被错误处理

答案 1 :(得分:0)

将您的WHERE更改为

WHERE ((`sender_id` = '111'
           AND `recipient_id` = '222')
       OR (`sender_id` = '222'
           AND `recipient_id` = '111')
      )
    AND ....

答案 2 :(得分:0)

也许这就是你想要的?

SELECT    <Insert columns names here as select * is a SQL antipattern>
FROM `messages` 
WHERE 
 (  
        (`sender_id` = '111' AND `recipient_id` = '222')
     OR (`sender_id` = '222' AND `recipient_id` = '111') 
  )
  AND 
  (
        (`is_message` != 'on' OR `is_message` IS NULL)
     OR (`mass_message` != 'on' OR `mass_message` IS NULL)
   )
  AND `invite_for_lunch` = 'on'
LIMIT 0 , 30