我有以下内容:
stock | Customer 12345 | NULL 12345 | ABC
我想要做的是删除第一个而不影响第二个,只要有一组这样的行:
if exists (select stock from table WHERE stock='12345' AND Customer is not null ) BEGIN DELETE FROM table WHERE stock= '12345' AND Customer is null END
该查询有效,但如何更改它以便我不必指定库存?我想保留与null客户的行是它是与该股票相关联的唯一值.
你可以使用exists:
DELETE t0 FROM table t0 WHERE Customer IS NULL AND EXISTS ( SELECT 1 FROM table t1 WHERE t0.stock = t1.stock AND t1.Customer IS NOT NULL )
这将仅删除客户为空的记录,并且至少有一条记录具有相同的库存ID.