在SQL中是否有任何约束,我添加一个值是一个表的外键,它从另一个表中删除该值(主键)?



我有两个表定义为:

dealership_inventory(vin, dealer_id, price, purchase_date)

vin为PK, dealer_id为FK

transactions(transaction_id, dealer_id, customer_id, vin, cpurchase_date, price)

其中transaction_id为PK, dealer_id、customer_id、vin为fk

每当我用插入语句向事务表添加一个新事务时,我希望从dealership_inventory表中删除具有匹配vin的元组。这在某种约束条件下可能吗?

您实际上并不需要从库存表中删除VIN号。相反,如果你想知道一辆车是否仍然可用,只需使用exists查询,例如

SELECT di.*
FROM dealership_inventory di
WHERE NOT EXISTS (
SELECT 1
FROM transactions t
WHERE t.vin = di.vin
);

如果,在稍后的某个时刻,库存表因不再可用的物品而陷入困境,您可以运行批处理作业,将这些已售出的物品移动到另一个表。

最新更新