Home > Mobile >  SQL query from Two tables and a link table to return all of table c for each row of table a with nul
SQL query from Two tables and a link table to return all of table c for each row of table a with nul

Time:10-11

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.

I have tried various ways of joining the tables but have failed to return what I need.

CodePudding user response:

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 Step Descr1 R
Role1 Step Descr2 R
Role1 Step Descr3 RW
Role2 Step Descr1 R
Role2 Step Descr2 none
Role2 Step Descr3 W
Role3 Step Descr1 none
Role3 Step Descr2 none
Role3 Step Descr3 none

db<>fiddle here

  • Related