【问题标题】:How to delete using joined value如何使用连接值删除
【发布时间】:2021-09-03 16:41:14
【问题描述】:

我遇到了两张类似这样的桌子

产品表 -

id product
1 product1
2 product2

product_inventory 表 -

product_id quantity
1 5
2 1
3 9

product_inventoryproduct_id 应该引用 productid 但假设它没有,所以我们Product inventory 表中有一个 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;

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

product.id product_inventory.product_id
1 5
2 1
NULL 9

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

【问题讨论】:

  • 类似于SELECT 的多表DELETE 可能会起作用。

标签: mysql sql performance


【解决方案1】:

你可以使用:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2012-07-14
    • 2012-02-12
    • 1970-01-01
    • 2021-10-18
    • 2021-07-11
    • 2021-09-07
    相关资源
    最近更新 更多