2014-01-14 133 views
0

該查詢返回is_message =「上」行和mass_message =「上」查詢不能返回正確的行

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_message,mass_message,invite_for_lunch)在同一行有on

預期結果:應該返回5行

+0

只有'invite_for_lunch ='on''你的其他支票呢?你在那裏放了很多OR。 –

+1

這看起來像它會做你想要的'AND invite_for_lunch ='on'',這是不是返回你期待的結果?你能發表一個你的源數據的例子,你期待什麼,你究竟得到了什麼? –

+1

我修復了縮進,這可以使識別邏輯問題更容易。 –

回答

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 

如果沒有額外的括號,第一或最有可能被不當

+0

TH返回零行,當它應該返回5 –

+0

原始查詢返回47行,並且它應該只返回5 –

+0

爲什麼你認爲它應該重新生成五條記錄? – HLGEM

0

更改您的WHERE

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

與@sparky的答案相同,並且返回相同的結果0行 –

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 
+0

我會試試這個並返回 –

+0

nope,結果相同。 –