我有一个复杂的SQLite查询,我可以使用一些帮助手工艺。我有5个表,每个表有3列。表1到表4的col3是table5 col1的外键。
我需要在表1到表4中选择col3的不同值,如果table5的col1不在选择结果中,则删除table5的col1。
Table1
col1 col2 col3
a b 1
c d 2
e f 1
Table2
col1 col2 col3
g h 2
i j 3
k l 4
m n 2
Table3
col1 col2 col3
b a 4
d c 3
o p 8
q r 1
Table4
col1 col2 col3
s t 2
u v 3
w x 4
Table5
col1 col2 col3
1 aa bb
2 cc dd
3 ee ff
4 gg hh
5 ii jj
6 kk ll
7 mm nn
8 oo pp
表1到表4中的不同集合将是。 1 2 3 4 8
将从table5中删除记录 五 6 7
据我所知,正在使用此代码收集选择集......
SELECT [table1].[col3], 1 as tablenumber
FROM [table1]
GROUP BY [table1].[col3_ID]
UNION ALL
SELECT [table2].[col3_ID], 2 as tablenumber
FROM [table2]
GROUP BY [table2].[col3_ID]
UNION ALL
SELECT [table3].[col3], 3 as tablenumber
FROM [table3]
GROUP BY [table3].[col3]
UNION ALL
SELECT [table4].[col3], 4 as tablenumber
FROM [table4]
GROUP BY [table4].[col3]
UNION ALL
我想在同一操作中删除table5中的记录。
答案 0 :(得分:1)
以下是获取要删除的ID列表的方法:
select *
from table5
where col1 not in (select col3 from table1 union
select col3 from table2 union
select col3 from table3 union
select col3 from table4
);
以下delete
应该可以实际删除它们:
delete from table5
where col1 not in (select col3 from table1 union
select col3 from table2 union
select col3 from table3 union
select col3 from table4
);
Here是一个SQL小提琴,可以显示它们的实际效果。
(原始答案不正确。原因之一是union
中子查询周围的额外括号。)
答案 1 :(得分:0)
您无法在同一操作中删除记录并将记录返回给您的应用程序。 你必须执行两个语句:
DELETE FROM Table5
WHERE col1 NOT IN (SELECT col3 FROM Table1 UNION
SELECT col3 FROM Table2 UNION
SELECT col3 FROM Table3 UNION
SELECT col3 FROM Table4);
SELECT col3 FROM Table1 UNION
SELECT col3 FROM Table2 UNION
SELECT col3 FROM Table3 UNION
SELECT col3 FROM Table4;
如果您希望它们是原子的,请将它们包装成transaction。