我想从t2删除如果在t1上不存在itemid,storeid,MSRTime的相同值,则t3上存在相同的itemid,storeid,MSRTime值,状态为D.在下面的示例中,我应该能够删除第二个排在t2但不是第1排。
表1:t1
itemid |storeid|MSRTime
x y z
表2:t2
itemid |storeid|MSRTime
x y z
a b c
表3:t3
itemid |storeid|MSRTime|status
x y z D
a b c D
我尝试使用join进行此操作,但无法达到预期效果。请帮忙。
谢谢。
答案 0 :(得分:1)
您几乎可以按照您的描述编写查询:
declare @t1 table(itemid varchar(7),storeid varchar(9),MSRTime varchar(3))
insert into @t1(itemid,storeid,MSRTime) values
('x','y','z')
declare @t2 table(itemid varchar(7),storeid varchar(9),MSRTime varchar(3))
insert into @t2(itemid,storeid,MSRTime) values
('x','y','z'),
('a','b','c')
declare @t3 table(itemid varchar(7),storeid varchar(9),MSRTime varchar(3),status varchar(4))
insert into @t3(itemid,storeid,MSRTime,status) values
('x','y','z','D'),
('a','b','c','D')
delete from t2
from @t2 t2
inner join
@t3 t3
on
t2.itemid = t3.itemid and
t2.storeid = t3.storeid and
t2.MSRTime = t3.MSRTime and
t3.status = 'D'
where
not exists (
select *
from @t1 t1
where t1.itemid = t2.itemid and
t1.storeid = t2.storeid and
t1.MSRTime = t2.MSRTime
)
select * from @t2
结果:
itemid storeid MSRTime
------- --------- -------
x y z
答案 1 :(得分:0)
应该是这样的
-- delete t2
select *
from table2 t2
JOIN table3 t3 on t2.itemid = t3.itemid and
t2.storeid = t3.storeid and
t2.MSRTime = t3.MSRTime
LEFT JOIN table1 t1 on t2.itemid = t1.itemid and
t2.storeid = t1.storeid and
t2.MSRTime = t1.MSRTime
where t1.itemID IS NULL
首先运行选择,如果它给你右后排,只需取消注释删除你就可以了
答案 2 :(得分:0)
我创建了整个脚本供您参考。请使用针对您的方案的最后一个DELETE查询。那就行了。
CREATE TABLE #T1
(itemid VARCHAR(10)
,storeid VARCHAR(10)
,MSRTime VARCHAR(10))
INSERT INTO #T1 VALUES ('x','y','z')
SELECT * FROM #T1
GO
CREATE TABLE #T2
(itemid VARCHAR(10)
,storeid VARCHAR(10)
,MSRTime VARCHAR(10))
INSERT INTO #T2 VALUES ('x','y','z'),('a','b','c')
SELECT * FROM #T2
GO
CREATE TABLE #T3
(itemid VARCHAR(10)
,storeid VARCHAR(10)
,MSRTime VARCHAR(10)
,status VARCHAR(10))
INSERT INTO #T3 VALUES ('x','y','z','D'),('a','b','c','D')
SELECT * FROM #T3
GO
DELETE M
FROM #T2 AS M INNER JOIN
(SELECT itemid,storeid,MSRTime FROM
(SELECT itemid,storeid,MSRTime FROM #T3 WHERE status='D') T1
INTERSECT
(SELECT itemid,storeid,MSRTime FROM
(SELECT * FROM #T2
EXCEPT
SELECT * FROM #T1) T2)) X
ON X.itemid = M.itemid AND X.storeid = M.storeid AND X.MSRTime = M.MSRTime
GO
答案 3 :(得分:0)
不确定这是否与您的环境匹配,但是通过编程方式将您与联接进行比较的结果限制为仅具有状态值D的那些结果可能是有益的。我也会尝试使用Coalese制作复合键,这样就不必在三个单独的连接上进行匹配。
例如 -
itemid |storeid|MSRTime|Key
x y z xyz
a b c abc