如何通过一个查询语句从两个相关表中获取矩阵表?

时间:2014-06-26 07:56:05

标签: mysql sql

enter image description here

如何通过一个查询语句从两个相关表中获取矩阵表,如图所示?或者我是否必须使用临时表?

2 个答案:

答案 0 :(得分:0)

我只是在用户和角色表之间使用CROSS JOIN来获得所有可能的组合,并且LEFT JOIN User_Role表以获得存在的匹配。

这将为每个用户/角色组合提供一个返回的行。然后,可以使用您正在使用的任何语言在表格中轻松输出。

SELECT User.id AS user_id, User.name, Role.role, IF(User_Role.role_id IS NULL, NULL, 'yes')
FROM User
CROSS JOIN Role
LEFT OUTER JOIN User_Role
ON User.id = User_Role.user_id
AND Role.id = User_Role.role_id
ORDER BY User.id, Role.id

答案 1 :(得分:0)

这是一个可能的解决方案,请注意解决方案是针对当前数据结构,如果角色表中有更多角色,那么它不是一个合适的解决方案。由于需要更改内部查询以适应新角色。

select 
id,
name,
coalesce(max(t.FW),'No') as FW,
coalesce(max(t.DF),'No') as DF,
coalesce(max(t.GK),'No') as GK,
coalesce(max(t.MF),'No') as MF
from user u
left join (
  select 
  case 
    when r.id = 1 AND ur.role_id is not null then 'Yes'
    else null
  end `FW`,

  case 
    when r.id = 2 AND ur.role_id is not null then 'Yes'
    else null 
  end `DF`,

  case 
    when r.id = 3 AND ur.role_id is not null then 'Yes'
    else null
  end `GK`,

  case 
    when r.id = 4 AND ur.role_id is not null then 'Yes'
    else null
  end `MF`,
  user_id
  from role r
  left join user_role ur on ur.role_id = r.id
)t
on t.user_id = u.id
group by u.id

我为空值添加了No,可以在

这样的语句中进行更改

coalesce(max(t.FW),'No') as FW,

因此,而不是只能添加' '

<强> DEMO