问题描述
我有下表:
-------------------------
| id | Person | Car |
| 1 | 1 | BMW |
| 2 | 1 | Ford |
| 3 | 1 | VW |
| 4 | 2 | BMW |
| 5 | 2 | Mercedes|
| 6 | 2 | VMW |
| 7 | 2 | FIAT |
-------------------------
这是我的挑战:
我想知道Person 2
拥有哪些汽车,而Person 1
没有。接下来,我要将这些汽车添加到Person 1
,然后,我需要删除Person 2。
有人可以告诉我查询的外观吗?
解决方法
create temporary table tabletemp like table1;
insert into tabletemp (Select * from table1 where Person=2 and table1.car not in (select car from table1 where person=1));
insert into table1 (Select null,1,car from tabletemp);
drop temporary table tabletemp;
我假设您的表名为table1,并且您的id列是自动增量列
,您需要表格的左连接:
select t2.car
from tablename t2 left join tablename t1
on t1.person = 1 and t2.car = t1.car
where t2.person = 2 and t1.car is null;
因此要在表格中插入汽车(假设id为自动递增):
insert into tablename(person,car)
select 1,t2.car
from tablename t2 left join tablename t1
on t1.person = 1 and t2.car = t1.car
where t2.person = 2 and t1.car is null;
然后删除人员2的行:
delete from tablename where person = 2;
请参见demo。