将这两个SQL语句合并为一个

问题描述 投票:0回答:3

我有两个表t1t2name, invoice, total列。

我正在使用此查询来获取T2中而不是T1中的行

select * 
from t2  
where name = (select source from info) 
except 
(select * from t1)

它工作正常并返回几行,我想要的是在一个语句中删除这些返回的行。

我已经尝试过了,但是它不仅删除了查询中返回的行,还删除了T2中的所有行。

delete from t2 
where exists ((select * 
               from t2  
               where name = (select source from info) 
               except 
               (select * from t1) 
             )) 

这里是我的数据示例:

T1

enter image description here

T2

enter image description here

返回的数据(名称为C2,在T2中,而不在T1中存在)

enter image description here

第三个表信息是获取名称,在这种情况下为C2。

提前感谢。

sql sql-server sql-delete sql-except
3个回答
1
投票

您可以通过左连接t2t1来做到这一点:

delete t
from (
  select * from t2
  where name = (select source from info)
) t left join t1
on t1.name = t.name and t1.invoice = t.invoice and t1.total = t.total
where t1.name is null

请参见demo。如果要使用NOT EXISTS

delete t
from (
  select * from t2
  where name = (select source from info)
) t 
where not exists (
  select 1 from t1
  where name = t.name and invoice = t.invoice and total = t.total
)

请参见demo。结果(行留在t2中):

> name | invoice | total
> :--- | ------: | ----:
> C1   |       1 |   150
> C1   |       2 |   300
> C2   |       1 |   200
> C2   |       2 |   165

1
投票

我正在使用此查询来获取T2中而不是T1中的行

我将使用的查询是:

select t2.*
from t2
where not exists (select 1 from t1 where t1.? = t2.name);

不清楚t1中匹配列的名称是什么。

很容易变成delete

delete from t2
where not exists (select 1 from t1 where t1.? = t2.name);

1
投票

您想通过两个条件从t2中删除:

  • 名称=(从信息中选择来源)
  • 行在t1中没有匹配项

声明:

delete from t2
where name = (select source from info)
and not exists
(
  select *
  from t1
  where t1.name = t2.name
    and t1.invoice = t2.invoice
    and t1.total = t2.total
);

或更短使用IN子句,仅在允许IN和元组的DBMS中可用:

delete from t2
where name = (select source from info)
and (name, invoice, total) not in (select name, invoice, total from t1);
© www.soinside.com 2019 - 2024. All rights reserved.