SQL多对多查询返回false

时间:2013-01-28 18:46:53

标签: mysql sql relational-database

我正在试图弄清楚如何执行多对多的SQL查询并遇到问题。

我的数据库结构是:

projects_users_roles: project_id, user_id, role_id
user_roles: id, name
projects: id, name, user_id

因此,在我的查询中,我想为user_id = 23选择所有项目,并在projects_users_roles

中为该项目分配了哪些角色名称

我以为我有它,但它返回FALSE

$query = "
SELECT p.name AS project_name
, r.name AS role_name
FROM projects AS p
JOIN projects_users_roles AS a
   ON a.project_id = p.id
JOIN users_roles AS role
   ON role.id = a.role_id WHERE a.user_id = 23
";
$result = mysql_query($query);
var_dump($result);

2 个答案:

答案 0 :(得分:6)

是否永远不会定义别名r?您的代码示例在r.name而不是SELECT中显示role.name

$query = "
SELECT p.name AS project_name
, role.name AS role_name
FROM projects AS p
JOIN projects_users_roles AS a
   ON a.project_id = p.id
JOIN users_roles AS role
   ON role.id = a.role_id WHERE a.user_id = 23
";
$result = mysql_query($query);
var_dump($result);

答案 1 :(得分:1)

您正在使用查询中不存在的别名r

SELECT  p.name AS project_name, 
        r.name AS role_name
FROM projects AS p
INNER JOIN projects_users_roles AS a
   ON a.project_id = p.id
INNER JOIN users_roles AS r
   ON r.id = a.role_id 
WHERE a.user_id = 23

而且,role可能是MySQL上的保留字。