首页 > 解决方案 > 如何使用连接值删除

问题描述

我遇到了两张这样的桌子

产品表 -

ID 产品
1 产品1
2 产品2

product_inventory表 -

product_id 数量
1 5
2 1
3 9

product_inventory表product_id应该引用产品id但假设没有,所以我们在Product 库存表中有一个 product_id (和数量),它与任何实际产品都不相关。现在想象一下有数十万个这样的无效值,所以我不能通过 id 手动删除它们。所以我发现这些使用右连接两个表是这样的:

SELECT  product.id, product_inventory.product_id
    FROM  product
    RIGHT JOIN  product_inventory  ON product.id=product_inventory.product_id
    where  product.id is NULL;

所以我得到这样的列表,例如

产品.id product_inventory.product_id
1 5
2 1
无效的 9

那么如何从product.id 为 NULL的product_inventory表中删除?

标签: mysqlsqlperformance

解决方案


您可以使用:

delete pi from product_inventory pi
    where not exists (select 1 from product p where p.id = pi.product_id);

您还应该了解外键关系以防止这种情况发生。


推荐阅读