我有这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;
我也尝试了这个,它也没有匹配(我几乎只包括前面的每个括号中的语句并添加了一个或在合并的语句中):
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'))
答案 0 :(得分:3)
它们不是同一个查询,因为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')
答案 1 :(得分:1)
这不起作用吗?:
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'))
OR ((t2.f4 = 'n') and t2.f5 < '2013-04-01' and t2.f6 in('sss','ttt','ddd'))
OR ((t2.f4 = 'n') and t2.f6 in('rrr','qqq','yyy'))
GROUP BY t2.f4, t2.f5, t2.f6;