我有这 3 个查询,它们几乎相同,除了 where 语句:
Insert into t1(f1,f2,f3)
SELECT t2.f1 AS f1, '' AS f2, t2.f2 AS f2, t3.f3 AS f3)
from t2
INNER JOIN t3 ON t2.f1 = t3.f1
WHERE (t2.f4 = 'n') and t2.f5 < '2013-04-01' and t2.f6 in('sss','ttt','ddd')
GROUP BY t2.f4, t2.f5, t2.f6;
Insert into t1(f1,f2,f3)
SELECT t2.f1 AS f1, '' AS f2, t2.f2 AS f2, t3.f3 AS f3)
from t2
INNER JOIN t3 ON t2.f1 = t3.f1
WHERE (t2.f4 = 'n') and t2.f5 > '2013-03-31' and t2.f6 in('sss','ttt','ddd')
GROUP BY t2.f4, t2.f5, t2.f6;
Insert into t1(f1,f2,f3)
SELECT t2.f1 AS f1, '' AS f2, t2.f2 AS f2, t3.f3 AS f3)
from t2
INNER JOIN t3 ON t2.f1 = t3.f1
WHERE (t2.f4 = 'n') and t2.f6 in('rrr','qqq','yyy')
GROUP BY t2.f4, t2.f5, t2.f6;
我不能像下面的查询那样组合它们,并且它们在理论上是相同的查询吗?因为我完全尝试了这个并且在测试结果时得到了不同的输出。
Insert into t1(f1,f2,f3)
SELECT t2.f1 AS f1, '' AS f2, t2.f2 AS f2, t3.f3 AS f3)
from t2
INNER JOIN t3 ON t2.f1 = t3.f1
WHERE (t2.f4 = 'n') and (t2.f5 < '2013-04-01' or t2.f5 > '2013-03-31' and t2.f6 in
('sss','ttt','ddd')) or t2.f6 in ('rrr','ggg','yyy')
GROUP BY t2.f4, t2.f5, t2.f6;
我也试过这个,但它也不匹配(我几乎只是将前面的每个 where 语句包含在括号中并在组合语句中添加一个 or ):
Insert into t1(f1,f2,f3)
SELECT t2.f1 AS f1, '' AS f2, t2.f2 AS f2, t3.f3 AS f3)
from t2
INNER JOIN t3 ON t2.f1 = t3.f1
WHERE ((t2.f4 = 'n') and t2.f5 < '2013-04-01' and t2.f6 in('sss','ttt','ddd')) or
((t2.f4 = 'n') and t2.f5 > '2013-03-31' and t2.f6 in('sss','ttt','ddd')) or ((t2.f4 = 'n') and t2.f6 in('rrr','qqq','yyy'))
最佳答案
它们不是同一个查询,因为 AND 优先于 OR。
所以在您第一次尝试重写时,您有:
(t2.f4 = 'n')
and (t2.f5 < '2013-04-01' or t2.f5 > '2013-03-31' and t2.f6 in ('sss','ttt','ddd'))
or t2.f6 in ('rrr','ggg','yyy')
任何满足第三行的东西都满足整个 where 子句。
换句话说,前两行需要括号:
((t2.f4 = 'n')
and (t2.f5 < '2013-04-01' or t2.f5 > '2013-03-31' and t2.f6 in ('sss','ttt','ddd')))
or t2.f6 in ('rrr','ggg','yyy')
关于mysql - SQL 多个 where 条件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20550666/