我创建了以下表格:
/sdcard -> /storage/self/primary
cd /storage/self
ls -la
primary -> /mnt/user/0/primary
cd /mnt/user/0/
我插入了以下数据:
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');
时。拥有" Louis"表not in
中至少有一辆车,查询显示我"路易斯"并且不应该显示"路易斯"。
我的查询:
accidents
结果:
select ID from people where ID in (select ID from cars where license_plate not in (select license_plate from accidents));
答案 0 :(得分: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。在此,您可以在人员表
上运行not in
查询
答案 1 :(得分:1)
我需要两个子查询
select id from people
where id not it
(select id form cars where licens_plate not in
(select distintc license_plate from accidents))
答案 2 :(得分: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