[英]Correct way to write sql join query for three table
假设我有三张桌子,
用户表
|-----|------|
| id | email|
|-----|------|
角色表
|-----|------|
| id | name |
|-----|------|
还有一个维护用户和角色关系的表
|----------|---------|
| user_id | role_id |
|----------|---------|
这里的问题是,如果我想知道用户是否具有特定角色(例如ADMIN
),
我做了这样的事情:
select * from user inner join (user_role innner join role on role.id = user_role.role_id and role.name = 'ADMIN') on user.id = user_role.user_id where user.email = 'xxxx@google.com';
当我在 mysql 中执行此 sql 时,它会向我报告Unknown column 'user_role.role_id' in 'on clause'
为什么? 正确的 sql 应该是什么?
此查询应适用于您请求的情况:
select
*
from
user
inner join
user_role on user.id = user_role.user_id
inner join
role on user_role.role_id = role.id
where
role.name = 'ADMIN'
and user.email = 'xxxx.google.com'
您在查询中错误地嵌套了您的joins
。 这就是引发错误的原因。 将您的查询与我上面的查询进行比较。
括号不在正确的 position 中,因此在它们之外,查询不知道“user_role”是什么。
尝试在内连接中不带括号,例如:
select * from user
inner join user_role on user.id = user_role.user_id
inner join role on (role.id = user_role.role_id and role.name = 'ADMIN')
where user.email = 'xxxx@google.com';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.