0

我有两张桌子t1t2有列name, 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

在此处输入图像描述

T2

在此处输入图像描述

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

在此处输入图像描述

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

提前致谢。

4

3 回答 3

1

您可以使用 to 的左连接来做到这t2一点t1

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

请参阅演示

如果你想使用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
)

请参阅演示

结果(剩余的行t2):

> name | invoice | total
> :--- | ------: | ----:
> C1   |       1 |   150
> C1   |       2 |   300
> C2   |       1 |   200
> C2   |       2 |   165
于 2019-10-26T11:43:49.527 回答
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);
于 2019-10-26T12:00:05.127 回答
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);
于 2019-10-26T11:14:44.773 回答