2016-05-05 25 views
2

我創建瞭如下表:如何在MYSQL中取得身份證?

create table people (
     ID    varchar(9), 
     name   varchar(20), 
     CONSTRAINT pk_ID PRIMARY KEY (ID) 
); 

create table cars (
     license_plate varchar(9), 
     ID    varchar(9), 
     CONSTRAINT pk_ID PRIMARY KEY (license_plate) 
); 

create table accidents (
     code   varchar(9), 
     license_plate varchar(9),  
     CONSTRAINT pk_ID PRIMARY KEY (code) 
); 

我插入了以下數據:

insert into people(ID, name) values('0x1','Louis'); 
insert into people(ID, name) values('0x2','Alice'); 
insert into people(ID, name) values('0x3','Peter'); 

insert into cars(license_plate, ID) values('001','0x1'); 
insert into cars(license_plate, ID) values('002','0x2'); 
insert into cars(license_plate, ID) values('003','0x1'); 
insert into cars(license_plate, ID) values('004','0x3'); 

insert into accidents(code, license_plate) values('fd1','001'); 
insert into accidents(code, license_plate) values('fd2','004'); 
insert into accidents(code, license_plate) values('fd3','002'); 

的問題是:如何選擇的人誰沒有任何他們的汽車有意外?

我的問題是,當我試圖使用not in。在「路易」至少有一輛車在表accidents中,查詢顯示爲「路易」,不應顯示「路易」。

我的查詢:

select ID from people where ID in (select ID from cars where license_plate not in (select license_plate from accidents)); 

結果:

+-----+ 
| ID | 
+-----+ 
| 0x1 | 
+-----+ 
+0

查找到'LEFT JOIN's。 – Siyual

+0

發佈您使用的SELECT查詢。 – WillardSolutions

+2

你如何連接3張桌子?我沒有看到汽車價值和事故之間的關係。 – scaisEdge

回答

3
select name from people where ID not in (
    select distinct c.ID from 
    accidents as a inner join cars as c 
    on a.license_plate = c.license_plate 
) 

說明=子查詢將加入汽車和事故,會給你所有的車誰了事故的ID。在此您可以運行在百姓餐桌

+0

它的作品完美,謝謝你:) – Python241820

1

not in查詢我需要兩個子查詢

 select id from people 
     where id not it 
      (select id form cars where licens_plate not in 
       (select distintc license_plate from accidents)) 
0

這應該是相當快:

SELECT people.* FROM people 
LEFT JOIN cars ON cars.ID = people.ID 
LEFT JOIN accidents ON accidents.license_plate = cars.license_plate 
WHERE accidents.code IS NULL 
GROUP BY people.ID 
相關問題