1

我未能在 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'

描述角色到用户:

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

描述角色:

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

2 回答 2

2

您不能像这样在外部使用内部选择中的列。r.id改为选择

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

顺便说一句,如果内部选择返回多于 1 条记录,则会失败。改用joina

select rtu.role_id
from roles r 
inner join roles_to_user rtu on rtu.role_id = r.id
where rtu.user_id = 1
于 2013-07-09T16:59:47.363 回答
0

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

于 2013-07-09T16:59:47.923 回答