日期:2014-05-18  浏览次数:20523 次

如何删除这种关系下的记录?
数据库中有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)的记录,查找未删除的进货单能看到相应的付款单,查找未删除的付款单能看到相应的进货单,这该怎么删呢?又或者怎么更改数据库的结构,删除时能达到这些要求?

------解决方案--------------------
SQL code
--> 测试数据: [进货]
if object_id('[进货]') is not null drop table [进货]
go
create table [进货] (进货单ID int,总额 int,支付余额 int)
insert into [进货]
select 1,100,0 union all
select 2,50,20 union all
select 3,200,170
--> 测试数据: [付款]
if object_id('[付款]') is not null drop table [付款]
go
create table [付款] (付款单ID int,总额 int,已付款 int)
insert into [付款]
select 1,50,0 union all
select 2,110,1
--> 测试数据: [映射]
if object_id('[映射]') is not null drop table [映射]
go
create table [映射] (映射表ID int,进货单ID int,付款单ID int,金额 int)
insert into [映射]
select 1,1,1,20 union all
select 2,1,2,80 union all
select 3,2,1,30 union all
select 4,3,2,30

select p.映射表ID,
    p.进货单ID,
    p.付款单ID,
    p.金额,
    i.支付余额,
    o.已付款  
from [映射] p 
join [付款] o on o.付款单ID=p.付款单ID
join [进货] i on i.进货单ID=p.进货单ID
--where i.支付余额=0 and 已付款=1


映射表ID       进货单ID       付款单ID       金额          支付余额        已付款
----------- ----------- ----------- ----------- ----------- -----------
1           1           1           20          0           0
2           1           2           80          0           1
3           2           1           30          20          0
4           3           2           30          170         1

(4 行受影响)

------解决方案--------------------
探讨

引用:

映射表ID 进货单ID 付款单ID 金额 支付余额 已付款

几个状态还不能满足你删除的条件?

能满足。但大多数多对多关系是这样描述:表1 映射关系 表2 ,表1、表2的记录不涉及删除,删除的是映射关系里的记录。
我的问题里进货单、付款单本身也涉及删除,即表1、表2……