2016-09-27 99 views
1

我需要顯示提出最大查詢次數的用戶及其部門的名稱。我通過加入5個表格來編寫以下查詢; user,query,profile,degreedepartment別名在查詢中不起作用

問題在於結果別名未被用於列名稱。對於這兩種列看起來像剛纔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 
+2

別名應該沒有單引號 –

回答

2

使用「爲」關鍵字,以便在MySQL中使用別名,並刪除單引號。

select user.name as USER_NAME from user; 
+0

使用AS試過了,還是一樣的結果 – PiGamma

+0

然後對錶名使用別名也和嘗試。 – Sagar

+0

您應該避免使用任何[保留名稱](https://dev.mysql.com/doc/refman/5.7/en/keywords.html),如果必須,請始終正確地打勾。 –

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; 

有時候,Mysql的喜歡你板着臉對你列一個別名,當您使用一些JOIN。

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 
+0

仍然沒有運氣.. – PiGamma

0

只需刪除從您的查詢報價,它會工作,但你可以使用關鍵字AS要清楚,你正在使用的別名。

我還要爲了避免與關鍵字的混亂,同時也使用大寫關鍵字使用小寫的別名;

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