Sql:在嵌套查询中使用别名

时间:2015-06-19 06:26:59

标签: mysql

select
    user.name,
    (select department.name
     from profile, degree, department
     where user.profile_id=profile.id
     and profile.degree_id=degree.id
     and degree.department_id=department.id) DEPT_NAME
from user, query
where user.id=query.user_id as USER_NAME
order by user.name;

这是我写的查询。对于department.name,列别名已更改为DEPT_NAME,但对于user.name,它没有更改,它会引发错误..请帮助......

2 个答案:

答案 0 :(得分:0)

将别名移至fields子句:

select
    `user`.name as USER_NAME,
    (select department.name
     from profile, degree, department
     where `user`.profile_id=profile.id
     and profile.degree_id=degree.id
     and degree.department_id=department.id LIMIT 1) DEPT_NAME
from `user`, query
where `user`.id=query.user_id
order by `user`.name;

此外,您的查询太重,请尝试更改并检查差异:

select u.name USER_NAME, dp.name DEPT_NAME
from `user` u
inner join query       q on  u.id = q.user_id
left  join profile     p on  p.id = u.profile_id
left  join degree      d on  d.id = p.degree_id
left  join department dp on dp.id = d.department_id
order by u.name;

答案 1 :(得分:-1)

试一试 -

SELECT usr.name User_Name,(SELECT dt.name FROM profile pf,degree dg,department dt WHERE usr.profile_id=pf.id AND pf.degree_id=dg.id AND dg.department_id=dt.id limit 1)DEPT_NAME FROM USER usr, QUERY qry WHERE usr.id=qry.user_id ORDER BY usr.name;

即使你可以使用下面的查询,这可以很快 -

SELECT user.name user_name,department.name AS DEPT_NAME 
FROM profile,degree,department,`user`,`query` 
WHERE user.profile_id=profile.id AND profile.degree_id=degree.id AND degree.department_id=department.id AND user.id=query.user_id ORDER BY user.name;