或其他条件之间的冲突

时间:2016-06-20 11:24:13

标签: mysql sql date select

我有以下查询:

float: right

问题是查询应该 ONLY 显示第一个和第二个'DateRecall'之间的行,但是返回所有包含'Call_Again','Busy'和'Not_answered'的行而不过滤约会。

任何解决方案都将不胜感激!

4 个答案:

答案 0 :(得分:47)

一个简单的IN()可以解决这个问题:

SELECT * FROM `Contacts` 
WHERE `Zona` = '1' 
    AND `Responsable` = '9' 
    AND `AllowComercialVisit` IN ('Call_Again','Busy','Not_answered') 
    AND `DateRecall` BETWEEN '2016-06-20 12:39:52'
                         AND '2016-06-20 13:04:52' 
ORDER BY `DateRecall` ASC
LIMIT 1

一般情况下,使用AND尝试使用括号时,OR优先于OR - >

WHERE COND1 AND COND2 AND (COND3 OR COND4) AND COND5

这将强制优化器遵循您的优先级而不是默认优先级。

答案 1 :(得分:12)

尝试以下查询:

SELECT * FROM `Contacts` 
WHERE `Zona` = '1' 
AND `Responsable` = '9' 
AND (`AllowComercialVisit` = 'Call_Again' OR `AllowComercialVisit` = 'Busy' OR AllowComercialVisit` = 'Not_answered')
AND `DateRecall` <= '2016-06-20 13:04:52' 
AND `DateRecall` >= '2016-06-20 12:39:52' 
ORDER BY `DateRecall` ASC 
LIMIT 1

用括号括起OR。

答案 2 :(得分:7)

尝试将OR语句分组,因为它们与同一列相关, 即。

SELECT * FROM `Contacts` 
WHERE `Zona` = '1' 
AND `Responsable` = '9' 
AND (`AllowComercialVisit` = 'Call_Again' 
OR `AllowComercialVisit` = 'Busy' 
OR `AllowComercialVisit` = 'Not_answered' ) 
AND `DateRecall` <= '2016-06-20 13:04:52' 
AND `DateRecall` >= '2016-06-20 12:39:52' 
ORDER BY `DateRecall` ASC LIMIT 1

答案 3 :(得分:0)

您可以使用IN()语句代替OR s:

SELECT * FROM `Contacts` 
WHERE `Zona` = '1' 
    AND `Responsable` = '9' 
    AND `AllowComercialVisit` IN('Call_Again','Busy','Not_answered')
    AND `DateRecall` <= '2016-06-20 13:04:52' 
    AND `DateRecall` >= '2016-06-20 12:39:52' 
    ORDER BY `DateRecall` ASC LIMIT 1