【问题标题】:MySQL - how can I find out what person two has but person one notMySQL - 我怎样才能找出第二个人有什么但第一个人没有
【发布时间】:2020-08-17 11:49:27
【问题描述】:

我有下表:

-------------------------
| 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。

谁能告诉我查询的样子?

【问题讨论】:

    标签: mysql sql compare


    【解决方案1】:

    你需要一个表的自左连接:

    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

    【讨论】:

    • 我可以通过 PDO 从我的 php 脚本的一个查询中运行它吗?
    • 您不能在 1 个查询中插入和删除。您必须分别运行最后两个查询。
    【解决方案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 列是一个自增列

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 2022-12-18
      • 2014-12-07
      • 2021-05-19
      相关资源
      最近更新 更多