如何删除这种关系下的记录?
数据库中有3个表,结构和记录如下:
进货:进货单ID 总额 支付余额
1 100 0
2 50 20
3 200 170
……
付款:付款单ID 总额 已付款
1 50 0
2 110 1
……
映射:映射表ID 进货单ID 付款单ID 金额
1 1 1 20
2 1 2 80
3 2 1 30
4 3 2 30
……
映射表的‘金额’指付款单ID对进货单ID支付的金额。
现在要删除3个表中满足条件(比如:进货:支付余额=0;付款:已付款=1)的记录,查找未删除的进货单能看到相应的付款单,查找未删除的付款单能看到相应的进货单,这该怎么删呢?又或者怎么更改数据库的结构,删除时能达到这些要求?
[解决办法]
--> 测试数据: [进货]if object_id('[进货]') is not null drop table [进货]gocreate table [进货] (进货单ID int,总额 int,支付余额 int)insert into [进货]select 1,100,0 union allselect 2,50,20 union allselect 3,200,170--> 测试数据: [付款]if object_id('[付款]') is not null drop table [付款]gocreate table [付款] (付款单ID int,总额 int,已付款 int)insert into [付款]select 1,50,0 union allselect 2,110,1--> 测试数据: [映射]if object_id('[映射]') is not null drop table [映射]gocreate table [映射] (映射表ID int,进货单ID int,付款单ID int,金额 int)insert into [映射]select 1,1,1,20 union allselect 2,1,2,80 union allselect 3,2,1,30 union allselect 4,3,2,30select p.映射表ID, p.进货单ID, p.付款单ID, p.金额, i.支付余额, o.已付款 from [映射] p join [付款] o on o.付款单ID=p.付款单IDjoin [进货] i on i.进货单ID=p.进货单ID--where i.支付余额=0 and 已付款=1映射表ID 进货单ID 付款单ID 金额 支付余额 已付款----------- ----------- ----------- ----------- ----------- -----------1 1 1 20 0 02 1 2 80 0 13 2 1 30 20 04 3 2 30 170 1(4 行受影响)
[解决办法]