我有一个mysql查询:
Select count(*) as cnt from page06 where dl = 1 and TYPE = 'mempage' union
Select count(*) as cnt from page06 where err = 1 and TYPE = 'mempage' union
Select count(*) as cnt from page06 where dl = 1 and err=1 and TYPE = 'mempage'
在大多数情况下,dl
和err
列为0,因此最后两个选择将返回0
。我发现这个查询只返回一个不符合我预期的查询。我找到了这个解决方案:
Select count(*) as cnt,'s' as p from page06 where dl = 1 and TYPE = 'mempage' union
Select count(*),'d' as p from page06 where err = 1 and TYPE = 'mempage' union
Select count(*),'f' as p from page06 where dl = 1 and err=1 and TYPE = 'mempage'
此查询工作正常但我已编写第一种格式的代码。我想知道为什么会发生这种情况,是否有任何解决方案(除了我所说的)来解决这个问题?
我不想使用我的解决方案的原因是我有很多书面查询,我不想(甚至不能)改变它们!我正在寻求的是设置为连接的选项之王(如set names 'latin1';
)
答案 0 :(得分:3)
使用UNION ALL
代替UNION
查看此帖子,了解有关差异的详细说明: What is the difference between UNION and UNION ALL?
SELECT count(*) AS cnt FROM page06 WHERE dl = 1 AND TYPE = 'mempage' UNION ALL
SELECT count(*) AS cnt FROM page06 WHERE err = 1 AND TYPE = 'mempage' UNION ALL
SELECT count(*) AS cnt FROM page06 WHERE dl = 1 AND err=1 AND TYPE = 'mempage'