看以下的SQL:
SELECT sum(`1`) FROM
(SELECT 1 from DUAL
UNION
SELECT 1 from DUAL
UNION
SELECT 2 from DUAL
UNION
SELECT 3 from DUAL) as t
执行的结果是什么?
开始以为是:7;但是事实是:6。
原因是:1重复了一次,Union将其合并为一条记录。
解决方法:使用Union All替换。
SELECT sum(`1`) FROM
(SELECT 1 from DUAL
UNION ALL
SELECT 1 from DUAL
UNION ALL
SELECT 2 from DUAL
UNION ALL
SELECT 3 from DUAL) as t