1

我有一个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'

在大多数情况下dlerr列是 0,所以最后两个 select 将返回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';

4

1 回答 1

3

使用UNION ALL代替UNION

查看此帖子以获取有关差异的详细说明: UNION 和 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'
于 2012-07-17T20:42:25.987 回答