从具有多个连接的两个不同表中选择两列[Mysql]

时间:2015-04-19 03:51:17

标签: mysql

我有四个表格users(id,name)roles(id,name)members(project_id,user_id,id)member_roles(member_id, role_id)。那么如何同时从这些表中选择users.name和roles.name(project_id是选择我们需要的名称的条件)?我可以单独选择users.name和roles.name但是当我连接两个查询时,我的代码失败了。这是获取users.name

的查询
select users.name from users
inner join members on members.user_id = users.id
where project_id = 1

这是获取roles.name

的查询
select roles.name from roles
inner join member_roles on member_roles.role_id = roles.id
join members on members.id = member_roles.member_id
where project_id = 1 

2 个答案:

答案 0 :(得分:1)

你快到了。另外,为了避免歧义,请在列Name上提供别名

SELECT  DISTINCT 
        u.Name AS member_name,
        r.Name AS role_name
FROM    users u
        INNER JOIN members m 
            ON u.id = m.user_id
        INNER JOIN member_roles mr
            ON m.id = mr.member_id
        INNER JOIN roles r
            ON r.id = mr.role_id
WHERE   m.project_id = 1

答案 1 :(得分:0)

如何连接2个查询?这样的事情怎么样:

select u.name as user_name, r.name as role_name from users u join members m on m.user_id = u.id join member_roles mr on mr.member_id = m.id join roles r on r.id = mr.role_id where m.project_id = 1;