2017-04-22 56 views
1

我的數據庫具有以下兩個表連接兩個MySQL表的基礎上正確條件

工作:

+----+--------------+ 
| id | name   | 
+----+--------------+ 
| 1 | Mechanic  | 
| 2 | Programmer | 
| 3 | Cleaner  | 
| 4 | Truck driver | 
+----+--------------+ 

資格:

+--------+--------------------+ 
| job_id | qualification  | 
+--------+--------------------+ 
|  1 | drivers_license | 
|  1 | engine_certificate | 
|  2 | mysql_certificate | 
|  4 | drivers_license | 
+--------+--------------------+ 

比方說,我有一個drivers_license和mysql_certificate 。我想創建一個SQL查詢,返回所有沒有我沒有的需求的作業。因此,查詢的結果應該是作業id 2,3和4

我曾嘗試以下查詢:

select * 
    from jobs j 
    join qualifications q 
    on j.id = q.job_id 
where q.qualification = 'drivers_license' || 
q.qualification = 'mysql_certificate'; 

這將返回id爲1,2和4,因此顯然是行不通的。

這怎麼能在SQL中實現?任何幫助是極大的讚賞。

回答

1

您可以使用group byhaving

select j.name, j.id 
from jobs j join 
    qualifications q 
    on j.id = q.job_id 
group by j.name, j.id 
having sum(q.qualification not in ('drivers_license' , 'mysql_certificate')) = 0;