How to use aliases in query for making conditions in mysql

吃可爱长大的小学妹 提交于 2019-12-24 02:06:27

问题


I have user table like as follows

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

I want to get total no of users and total no of male users ans percent for male and female users

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;

This query is not working when using aliases to calculate male and female percent. I am getting the error like 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;

But this is working.

But is this i used SUM(IF(v.gender = 'Female',1,0)) 2 times.I think it will degrade the performance.

Can't i use aliases in my situation ?

Thanks in advance...


回答1:


Your query is just fine. You can't use an alias at a select level. Your only option would be to have a derived table but that will indeed degrade performance.

Just one thing to improve the query performance would be to change the Gender column into just a boolean or char column.

Tip: All non-null boolean comparisons in MySQL resolve to 1 (true) and 0 (false), so you could simplify your query this way:

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



回答2:


Add inner query like this.

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;


来源:https://stackoverflow.com/questions/19150899/how-to-use-aliases-in-query-for-making-conditions-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!