从table1删除元组的最聪明的方法是什么,在第二个表中, 如果第二个表不是初始数据库的一部分,而是一些非常大的查询结果?
table1 *this table is a result of some query
------------- -------------
| id1 | id2 | | id1 | id2 |
------------- -------------
| 1 2 | | 5 6 |
| 3 4 | | 1 2 |
| 5 6 | | 11 12 |
| 7 8 | -------------
| 9 10 |
| 11 12 |
| 13 14 |
-------------
我想出了
delete from table1
where id1 in (select id1 from ( really long query to get a second table))
and id2 in (select id2 from (the same really long query to get a second table));
它有效,但我觉得我做得太错了,并没有保持查询DRY。
如果table1有一个额外的列,你建议的工作方式是否相同,例如“somecol”?
答案 0 :(得分:2)
IMO,您可以使用EXISTS
这样的语句:
DELETE FROM table1
WHERE EXISTS (
SELECT 1
FROM (<your long query>) AS dt
WHERE table1.id1 = dt.id1
AND table1.id2 = dt.id2);
<强> [SQL Fiddle Sample] 强>
答案 1 :(得分:1)
使用EXISTS
的相关子查询允许匹配多个列:
delete
from table1
where exists
( select * from
(
"really long query"
) as t2
where table1.id1 = t2.id1 -- correlating inner and outer table
and table1.id2 = t2.id2 -- similar to a join-condition
)
答案 2 :(得分:1)
一种方法是使用delete
,exists
和with secondtable as (
<your query here>
)
delete from table1
where exists (select 1
from secondtable st
where table1.id1 = st.id1 and table1.id2 = st.id2
);
:
TextBox.Clear();
TextBox.Text = string.Empty;