0

私は複雑な SQLite クエリを持っています。それぞれ 3 つの列を持つ 5 つのテーブルがあります。テーブル 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 から削除されたレコードは 5 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 からレコードを削除したいと思います。

4

2 に答える 2

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
                 );

これは、実際にそれらを示す SQL Fiddle です

(元の回答は正しくありませんでした。その理由の 1 つは、 のサブクエリを囲む余分な括弧のセットでしたunion。)

于 2013-09-12T12:57:38.893 に答える