我的查询存在问题,
SELECT *
FROM requests
WHERE date = '2014/05/18' AND payorTown = 'Malolos'
OR payeeTown ='Malolos' OR payorTown != 'Malolos' OR payeeTown != 'Malolos'
ORDER BY typeOfAssistance`
我有类似的东西,但是MySQL忽略了第一个条件date = '2014/05/18'
我很确定没有匹配相同date
的记录。但结果出现了许多符合条件AND payorTown = 'Malolos' OR payeeTown ='Malolos' OR payorTown != 'Malolos' OR payeeTown != 'Malolos'
的记录。
是否有关于在WHERE CLAUSE中声明条件的规则?
答案 0 :(得分:1)
您需要整理您的目标条件,您当前的查询忽略了标准,例如(日期和payorTown --->或)您需要通过对组中的所有ors分组您和标准或标准或者某些或......)
SELECT * FROM requests
WHERE date = '2014/05/18' AND
(
(payorTown = 'Malolos' OR payeeTown ='Malolos') OR
(payorTown != 'Malolos' OR payeeTown != 'Malolos')
)
ORDER BY typeOfAssistance
答案 1 :(得分:1)
组合AND& OR条件,使用括号非常重要,以便数据库知道评估每个条件的顺序。 (就像你在学习Math课程中的操作顺序一样!)
SELECT *
FROM requests
WHERE date='2014/05/18 AND
(
payorTown = 'Malolos' OR
payeeTown ='Malolos' OR
payorTown != 'Malolos' OR
payeeTown != 'Malolos'
)
ORDER BY typeOfAssistance
在您的情况下,它没有意义,因为括号中的条件总是返回true。您可能希望在括号中的某处使用AND
。
我想,你是这样的:
SELECT *
FROM requests
WHERE date = '2014/05/18' AND
(payorTown = 'Malolos' AND payeeTown ='Malolos') OR
(payorTown != 'Malolos' AND payeeTown != 'Malolos')
ORDER BY typeOfAssistance
<强>解释强>
除日期条件外,如果记录满足以下条件之一,此查询将选择记录:
答案 2 :(得分:1)
AND
比OR
更难绑定(优先级更高),因此您的条件生效;
WHERE date = ('2014/05/18' AND payorTown = 'Malolos')
OR payeeTown ='Malolos' OR payorTown != 'Malolos' OR payeeTown != 'Malolos'
也就是说,您的日期条件仅与payorTown = 'Malolos'
合并,无论日期如何,都会返回来自其他条件的匹配。
我只能猜测你对查询的真正含义,但解决方案只是使用括号来覆盖默认优先级,例如(有点荒谬);
WHERE date = '2014/05/18' AND
(payorTown = 'Malolos' OR payeeTown = 'Malolos' OR
payorTown != 'Malolos' OR payeeTown != 'Malolos')
答案 3 :(得分:1)
SELECT * FROM requests
WHERE date = '2014/05/18' AND
(payorTown = 'Malolos' AND payeeTown ='Malolos') OR
(payorTown != 'Malolos' AND payeeTown != 'Malolos')
ORDER BY typeOfAssistance