Quantcast
Viewing latest article 2
Browse Latest Browse All 3

Answer by Strawberry for Selecting ALL from a specific range

DROP TABLE IF EXISTS employees;CREATE TABLE employees (employee_id SERIAL PRIMARY KEY);DROP TABLE IF EXISTS employee_project;CREATE TABLE employee_project (employee_id INT NOT NULL, project_id INT NOT NULL,PRIMARY KEY(employee_id,project_id));DROP TABLE IF EXISTS projects;CREATE TABLE projects(project_id SERIAL PRIMARY KEY, department_id INT NOT NULL);INSERT INTO employees VALUES (101),(102),(103);INSERT INTO employee_project VALUES (101,5004),(101,5005),(101,5006),(101,5007),(102,5004),(102,5007),(102,5008),(103,5006),(103,5007),(103,5008);INSERT INTO projects VALUES (5004,1),(5005,2),(5006,5),(5007,5),(5008,4),(5009,3);Consider the following:SELECT *   FROM employees e   JOIN projects p   LEFT   JOIN employee_project ep     ON ep.employee_id = e.employee_id    AND ep.project_id = p.project_id  WHERE p.department_id = 5;+-------------+------------+---------------+-------------+------------+| employee_id | project_id | department_id | employee_id | project_id |+-------------+------------+---------------+-------------+------------+|         101 |       5006 |             5 |         101 |       5006 ||         102 |       5006 |             5 |        NULL |       NULL ||         103 |       5006 |             5 |         103 |       5006 ||         101 |       5007 |             5 |         101 |       5007 ||         102 |       5007 |             5 |         102 |       5007 ||         103 |       5007 |             5 |         103 |       5007 |+-------------+------------+---------------+-------------+------------+

From this result, we can make two observations, either of which could prove helpful in solving the problem.

  1. The number of distinct projects in the result is equal to the number of distinct projects listed alongside users 101 and 103 (i.e., the number of times those numbers appear in column 4).
  2. User 102 has a null result, which means that they're not involved in all of that department's projects.

Viewing latest article 2
Browse Latest Browse All 3

Trending Articles