2

I am trying to figure out how to do many to many sql queries and have hit an issue.

My db structure is:

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

So in my query I would like to select all projects for user_id=23 and what role name they have been assigned on that project in projects_users_roles

I thought I had it but its returning 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);
4

2 回答 2

6

难道r是从来没有定义别名?您的代码示例显示r.nameSELECT而不是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);
于 2013-01-28T18:50:36.823 回答
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 上的保留字。

于 2013-01-28T18:51:28.447 回答