2014-10-20 49 views
1

我想要显示一个输出表,用于统计在表中找到的所有用户。 基本上我想输出的样子:Mysql为不同的where子句显示不同的列

+-----------+-----------+ 
| user1  | user2  | 
+-----------+-----------+ 
|   5 |   2 | 
+-----------+-----------+ 

我只是用一个虚表来进行测试。我的查询是这样的:

(
    select 
     name as user1 
    from 
     users 
    where 
     name = 'root' 
) UNION (
    select 
     name as user2 
    from 
     users 
    where 
     name = 'not_root' 
) 

其中仅输出是这样的:

+-----------+ 
| user1  | 
+-----------+ 
|   5 | 
|   2 | 
+-----------+ 

回答

0

EDITED

该方法的主要思想是将表视为子查询中的两个不同的虚拟表。我们可以制作嵌套的选择语句,例如(select count(*) as c from users where name = 'root') u1 MySql将其视为名为u1的特定表,其中一行一列名为c

select u1.c as root_cnt, u2.c as not_root_cnt 
from (select count(*) as c from users where name = 'root') u1, 
(select count(*) as c from users where name = 'not_root') u2 

此外,如果你有一个返回只有一行,你可以直接把嵌套选择在字段中选择语句列表这样的做法是额外的子查询的

select (select count(*) as c from users where name = 'root') as root_cnt, (select count(*) as c from users where name = 'not_root') as not_root_cnt 

定劣势。基于使用case when构造的方法没有这样的缺点。

+0

这其实给我的我正在找的答案。你能否为此添加一些描述?我想明白为什么会发生这种情况,因为我是一个新手。 – clueless 2014-10-21 02:05:32

+0

另外,我不能让'count(u1。*)'工作(语法错误),我不得不使用'count(u1.name)'。 – clueless 2014-10-21 02:06:41

+0

@DumbAsker确实看起来像count(u1。*)不起作用。我使用相同的方法改进了查询并添加了另一个。 – triclosan 2014-10-21 08:41:42

0

您可以使用case声明count内获得数在单独的列

select 
    count(case when name = 'root' then 1 end) user1, 
    count(case when name = 'not_root' then 1 end) user2 
from users 
where name in ('root','not_root') 
0

看来你的查询是错的..

工会不会合并两个查询的结果,你有上述的方式。

联合会结合两个或更多select语句的结果,但不会“加入”它。

您可能想要为此使用连接。还是你不能够把5 | 2同一行,因为它基本上暗示 - >获取用户1和用户2个值的一种特定类型

1

试试这个

SELECT 
    SUM(CASE WHEN Name = 'root' THEN 1 ELSE 0 END) user1, 
    SUM(CASE WHEN Name = 'not_root' THEN 1 ELSE 0 END) user2 
FROM Users 
相关问题