3

我有user如下表

user_id    name    gender    age
--------------------------------
1          AAA      Male      45
2          BBB      Female    22
3          CCC      Male      47
.................................
..............................

我想获得用户总数和男性用户总数以及男性和女性用户的百分比

select count(*) as total , SUM(IF(v.gender = 'Male',1,0)) as totalMale ,
   SUM(IF(v.gender = 'Female',1,0)) as totalFemale , totalMale/total *100 ,
   totalFeMale/total *100 from user;

使用别名计算男性和女性百分比时,此查询不起作用。我收到类似的错误 unknown columns..........

select count(*) as total , SUM(IF(v.gender = 'Male',1,0)) as totalMale ,
SUM(IF(v.gender = 'Female',1,0)) as totalFemale , SUM(IF(v.gender = 'Male',1,0))/count(*) *100 ,SUM(IF(v.gender = 'Female',1,0))/count(*) *100 from user;

但这是有效的。

但这是我使用SUM(IF(v.gender = 'Female',1,0))了 2 次吗?我认为它会降低性能。

我不能在我的情况下使用别名吗?

提前致谢...

4

2 回答 2

1

您的查询很好。您不能在选择级别使用别名。您唯一的选择是拥有一个派生表,但这确实会降低性能。

提高查询性能的一件事就是将 Gender 列更改为 boolean 或 char 列。

提示:MySQL 中的所有非空布尔比较解析为 1 (true) 和 0 (false),因此您可以通过以下方式简化查询:

select
    count(*) total,
    SUM(gender = 'Male') totalMale,
    SUM(gender = 'Female') totalFemale,
    SUM(gender = 'Male') / count(*) * 100 percentageMale,
    SUM(gender = 'Female') / count(*) * 100 percentageFemale
from user
于 2013-10-03T04:52:59.260 回答
0

像这样添加内部查询。

Select t1.total ,
t1.totalMale/total *100 ,
t1.totalFeMale/t1.total *100  
from 
(select 
count(user_id) as total , 
SUM(IF(v.gender = 'Male',1,0)) as totalMale ,
SUM(IF(v.gender = 'Female',1,0)) as totalFemale 
from user)t1;
于 2013-10-03T04:48:34.777 回答