mysql查询错误1054 - 未知列

时间:2013-07-09 16:58:07

标签: mysql sql

我无法在mysql中运行查询。故意我不想做select id from roles ...

查询

select rtu.role_id
from roles r 
where id =(select role_id 
           from roles_to_user rtu 
           where user_id=1)

错误

ERROR 1054 (42S22): Unknown column 'rtu.role_id' in 'field list'

desc roles_to_user:

+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| user_id | int(11) | NO   | PRI | NULL    |       |
| role_id | int(11) | NO   | PRI | NULL    |       |
+---------+---------+------+-----+---------+-------+

desc角色:

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(80) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

2 个答案:

答案 0 :(得分:2)

您不能像这样使用其外部内部选择的列。选择r.id代替

select r.id
from roles r 
where id = (select role_id 
            from roles_to_user rtu 
            where user_id = 1)
如果内部选择返回多于1条记录,则BTW将失败。请改用join

select rtu.role_id
from roles r 
inner join roles_to_user rtu on rtu.role_id = r.id
where rtu.user_id = 1

答案 1 :(得分:0)

您的别名rtu仅在子查询中可用,而不在主子查询中。