[英]SQL query from Two tables and a link table to return all of table c for each row of table a with nulls where the is no link in table b
Given the schema:给定架构:
Table a: worker_role_desription,role
Linking Table b: role,stepid, permission
Table c: stepid, step_description
I need to return a full list of step_descriptions
from c
for each role from a
with the permission from b
if it exists and 'none'
if it doesn't.我需要从
c
为每个角色返回a
完整的step_descriptions
列表,如果它存在则获得b
的许可,如果不存在则返回'none'
。
I have tried various ways of joining the tables but have failed to return what I need.我尝试了各种加入表格的方法,但未能返回我需要的内容。
You want something like:你想要这样的东西:
SELECT worker_role,
step_description,
COALESCE(permission, 'none') AS permission
FROM a
CROSS JOIN c
LEFT OUTER JOIN b
ON (a.role = b.role AND c.stepid = b.stepid)
ORDER BY
a.role,
c.stepid
Which, for the sample data:其中,对于样本数据:
CREATE TABLE a (worker_role, description, role PRIMARY KEY) AS
SELECT 'Role'|| LEVEL, 'Role Descr'||LEVEL, LEVEL FROM DUAL CONNECT BY LEVEL <= 3;
CREATE TABLE c (stepid PRIMARY KEY, step_description) AS
SELECT LEVEL, 'Step Descr'||LEVEL FROM DUAL CONNECT BY LEVEL <= 3;
CREATE TABLE b(role, stepid, permission) AS
SELECT 1, 1, 'R' FROM DUAL UNION ALL
SELECT 1, 2, 'R' FROM DUAL UNION ALL
SELECT 1, 3, 'RW' FROM DUAL UNION ALL
SELECT 2, 1, 'R' FROM DUAL UNION ALL
SELECT 2, 3, 'W' FROM DUAL;
ALTER TABLE b
ADD CONSTRAINT b__role__fk FOREIGN KEY (role) REFERENCES a(role)
ADD CONSTRAINT b__stepid__fk FOREIGN KEY (stepid) REFERENCES c(stepid);
Outputs:输出:
WORKER_ROLE 工人角色
STEP_DESCRIPTION 步骤_描述
PERMISSION 允许
Role1 角色1
Step Descr1 步骤描述 1
R R
Role1 角色1
Step Descr2 步骤描述 2
R R
Role1 角色1
Step Descr3 步骤描述3
RW 读写器
Role2 角色2
Step Descr1 步骤描述 1
R R
Role2 角色2
Step Descr2 步骤描述 2
none 没有任何
Role2 角色2
Step Descr3 步骤描述3
W W
Role3 角色3
Step Descr1 步骤描述 1
none 没有任何
Role3 角色3
Step Descr2 步骤描述 2
none 没有任何
Role3 角色3
Step Descr3 步骤描述3
none 没有任何
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.