Sql 查询未返回正确的行

Sql 查询未返回正确的行,sql,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_me

此查询返回具有
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
如何确保它只返回包含“邀请您共进午餐”的行

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
这本来是一个计数,但我想看看返回了哪些行

我检查了列,并且(
is_message
mass_message
invite_for_午餐
)中没有两列在同一行中


预期结果:应返回5行

尝试修复括号

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
如果没有额外的括号,第一个或第二个最有可能被错误处理

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

也许这就是你想要的

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
选择
来自“消息”
哪里
(  
(`sender\u id`=“111”和`recipient\u id`=“222”)
或(`sender\u id`=“222”和`recipient\u id`=“111”)
)
及
(
('is_message`!='on'或'is_message`为空)
或(`mass\u message`!=“on”或`mass\u message`为空)
)
和“邀请你共进午餐”='on'
限制0,30

Only
邀请您共进午餐='on'
您的其他支票呢。你在那里放了很多ORs。这看起来会做你想要的
并邀请你吃午饭='on'
,这不是返回你期望的结果吗?你能举一个你的源数据的例子吗,你期望的和你实际得到的是什么?我修复了缩进,这将使识别逻辑问题变得更容易。你可能遇到了运算符优先级问题。您可以使用一些额外的括号。如果您发布了一些示例数据和所需的结果,这会有所帮助。它返回零行,而它本应返回5行。原始查询返回47行,同样,它应该只返回5条记录,为什么你认为它应该重新返回5条记录?@HLGEM我对
invite\u for\u午餐
设置为“on”的行进行了手动计数@sparky我将使用两个带count的查询并添加结果,因为我学到了一些新内容,所以接受你的答案。答案与@sparky相同,返回相同的结果0行。我将尝试此操作并返回。