如何在查询中使用别名来创建mysql中的条件

时间:2013-10-03 04:39:11

标签: mysql alias

我有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次。我认为这会降低性能。

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

提前致谢...

2 个答案:

答案 0 :(得分:1)

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

改善查询性能只需要将Gender列更改为boolean或char列。

提示:MySQL中的所有非空布尔比较都解析为1(真)和0(假),因此您可以这样简化查询:

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

答案 1 :(得分: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;