SQL查询 - 如何找到在所有项目中工作的工程师

时间:2017-12-25 10:22:01

标签: mysql sql

我有3个表,工程师(id,名称),项目(id,名称,描述),works(engineer_id,project_id),我想找到在所有项目中工作的工程师

感谢。

2 个答案:

答案 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);

Sample demo

其工作原理如下:

  • 加入三张桌子。
  • 按工程师ID和名称分组。
  • 拥有子句,只选择那些项目ID等于项目表中项目总数的那些。

答案 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)