我有3个表,工程师(id,名称),项目(id,名称,描述),works(engineer_id,project_id),我想找到在所有项目中工作的工程师
感谢。
答案 0 :(得分:0)
试试这个:
SELECT e.id, e.name
FROM engineer as e
INNER JOIN works as w ON e.id = w.engineer_id
GROUP BY e.id, e.name
HAVING COUNT(w.project_id) = (SELECT COUNT(*) FROM project);
其工作原理如下:
答案 1 :(得分:0)
不需要像我们已经做的那样进行INNER JOIN PROJECT SELECT COUNT(*)FROM project
在下面找到带有数据的SQL
WITH engineer AS (
SELECT 1::int AS id, 'a'::VARCHAR AS name
UNION
SELECT 2::int AS id, 'b'::VARCHAR AS name
UNION
SELECT 3::int AS id, 'c'::VARCHAR AS name
),
project AS (
SELECT 1::int AS id, 'p1'::VARCHAR AS name
UNION
SELECT 2::int AS id, 'p2'::VARCHAR AS name
UNION
SELECT 3::int AS id, 'p3'::VARCHAR AS name
UNION
SELECT 4::int AS id, 'p4'::VARCHAR AS name
),
works AS (
SELECT 1::int AS eng_id, 1::int project_id
UNION
SELECT 1::int AS eng_id, 2::int project_id
UNION
SELECT 2::int AS eng_id, 1::int project_id
UNION
SELECT 2::int AS eng_id, 3::int project_id
UNION
SELECT 2::int AS eng_id, 2::int project_id
UNION
SELECT 3::int AS eng_id, 2::int project_id
)
SELECT
e.id,
e.name
FROM
engineer AS e
INNER JOIN works AS w ON (e.id = w.eng_id)
GROUP BY
e.id,
e.name
HAVING COUNT(w.project_id) = (SELECT COUNT(*) FROM project)