简体   繁体   English

SQL 查询来自两个表和一个链接表,以返回表 c 的所有表 a 的每一行,其中表 b 中没有链接

[英]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没有任何

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM