如何解决MySQL-如何找出第二个人有什么但第一个人没有
我有下表:
-------------------------
| 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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。