2015-03-19 12 views
1

兩個表。一對多。如何找到絕對所有員工都在IT部門工作並且薪水超過$ 150000的所有公司?SQL:查找具有全部符合特定條件的引用行的所有行

[COMPANIES] 

|----|--------------| 
| id | company_name | 
|----|--------------| 
| 1 | Google  | 
| 2 | Apple  | 
|----|--------------| 

[EMPLOYEES] 

|----|------------|------|------------|--------| 
| id | company_id | name | department | salary | 
|----|------------|------|------------|--------| 
| 1 | 1   | John | IT   | 200000 | 
| 2 | 1   | Bob | IT   | 200000 | 
| 3 | 2   | Rick | Design  | 100000 | 
| 4 | 2   | Bill | Design  | 100000 | 
|----|------------|------|------------|--------| 

回答

2

你可以使用EXISTS + NOT EXISTS

SELECT c.* 
FROM COMPANIES c 
WHERE EXISTS 
(
    SELECT 1 FROM EMPLOYEES e 
    WHERE e.company_id = c.id 
    AND e.salary > 150000 
    AND e.department = 'IT' 
) 
AND NOT EXISTS 
(
    SELECT 1 FROM EMPLOYEES e 
    WHERE e.company_id = c.id 
    AND (e.salary <= 150000 OR e.department <> 'IT') 
) 

Demo

2

我認爲你可以得到你想要使用having條款的內容:

select company_id 
from employees 
group by company_id 
having min(department) = max(department) and 
     min(department) = 'IT' and 
     min(salary) >= 150000; 

如果你希望公司的名字,你可以加入在:

select c.id, c.company_name 
from companies c join 
    employees e 
    on c.id = e.company_id 
group by c.id, c.company_name 
having min(department) = max(department) and 
     min(department) = 'IT' and 
     min(salary) >= 150000; 
+0

@CL。 。 。 。謝謝。 – 2015-03-19 23:02:52

相關問題