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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...