如何在查询中包含一个列,以显示项是否存在于另一个表中?

时间:2016-09-27 18:25:16

标签: sql join many-to-many

我正在拥抱我希望暂时失误的推理。我有以下架构:

schema

SELECT RoleName FROM aspnet_Roles; gives:
-----------------------------------------
Administrator
Backend
Business Manager
Content Editor
Employee
Salesperson

SELECT RoleName FROM aspnet_Roles r INNER JOIN admin_page_role apr ON r.RoleId = apr.RoleId WHERE apr.PageId = 4;
------------------------------------------
Administrator
Business Manager
Salesperson

我想要的是第一个查询的完整列表以及是否分配了角色,例如:

| RoleName        |  IsAssignedToPage
---------------------------------------
Administrator             1
Backend                   0
Business Manager          1
Content Editor            0
Employee                  0
Salesperson               1

我查看了How to write a MySQL query that returns a temporary column containing flags...这有意义,但我的admin_page_role表是一个可以包含许多页面角色组合的桥接表。

1 个答案:

答案 0 :(得分:2)

这样的事情:

SELECT RoleName, case when apr.roleid is null then 0 else 1 end as IsAssignedToPage   
FROM aspnet_Roles r   
LEFT JOIN admin_page_role apr ON r.RoleId = apr.RoleId and apr.PageId = 4