别名不在查询中工作

时间:2016-09-27 09:01:45

标签: mysql alias

我需要显示已提出最大查询数的用户及其部门的名称。我通过加入5个表编写了以下查询; userqueryprofiledegreedepartment

问题在于结果别名没有用于列名。对于这两列,它只显示为name

select user.name 'USER_NAME',department.name 'DEPT_NAME'
from user
inner join query on (query.user_id=user.id)
inner join profile on (user.profile_id=profile.id)
inner join degree on (profile.degree_id=degree.id)
inner join department on (degree.department_id=department.id)
group by user.name
order by count(query.id) desc
limit  1

4 个答案:

答案 0 :(得分:2)

使用'as'关键字以便在mysql中使用别名,并删除单引号。

select user.name as USER_NAME from user;

答案 1 :(得分:1)

以下语法对我来说非常合适:

select U.name AS "USER_NAME", D.name AS "DEPT_NAME"
from user U
inner join query Q on (Q.user_id=U.id)
inner join profile P on (U.profile_id=P.id)
inner join degree C on (P.degree_id=C.id)
inner join department D on (C.department_id=D.id)
group by U.name
order by count(Q.id) desc
limit  1;

有时,当您使用某些JOIN时,Mysql更喜欢在列上输出别名。

答案 2 :(得分:1)

以这种方式试试;

select thisuser.name 'USER_NAME',department.name 'DEPT_NAME'
from user as  thisuser
inner join query on (query.user_id=thisuser.id)
inner join profile on (thisuser.profile_id=profile.id)
inner join degree on (profile.degree_id=degree.id)
inner join department on (degree.department_id=department.id)
group by thisuser.name
order by count(query.id) desc
limit  1

但是在构造查询时这不是一个好习惯; 看起来像这样

select thisuser.name,thisdept.name from
(select name,user_id from user) as thisuser
inner join
(select name,user_id from department) as thisdept
on thisuser.user_id = thisdept.user_id 

答案 3 :(得分:0)

只需从查询中删除引号即可,但您可以使用关键字AS来明确表示您正在使用别名。

我还会使用小写别名以避免与关键字混淆,并且还会为关键字使用大写字母;

SELECT user.name AS user_name, department.name AS dept_name
...