mysql - 如何使用连接值删除
问题描述
我遇到了两张这样的桌子
产品表 -
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表中删除?
解决方案
您可以使用:
delete pi from product_inventory pi
where not exists (select 1 from product p where p.id = pi.product_id);
您还应该了解外键关系以防止这种情况发生。
推荐阅读
- c# - 如何在 asp.net C# 中实现 SAML SSO 2.0
- tensorflow - Tensorflow 需要很长时间才能连接到 Nvidia-Drivers
- android - Viewpager2 占用全屏的约束布局
- c# - 为什么 Math.Round() 会根据架构(x86 与 x64)进行不同的舍入?
- javascript - 获取输入类型“文本”的动态值
- bash - 使用命令行数据块提交具有不同参数的作业
- c# - 如何概括代码以在 WPF 应用程序中每个窗口只允许一个实例
- vhdl - Basys2 FPGA板上的VHDL简单七段显示
- apache-spark - 如何在流式传输 Dataframe 时读取和显示示例(10)记录?
- javascript - 按对象数组分组