他のテーブルに同じIDが存在するものを抽出するSQLの例です。
【SQL】
SELECT id FROM (
SELECT id, 'table1' AS tablename FROM table1
UNION ALL
SELECT id, 'table2' AS tablename FROM table2
UNION ALL
SELECT id, 'table3' AS tablename FROM table3
UNION ALL
SELECT id, 'table4' AS tablename FROM table4
UNION ALL
SELECT id, 'table5' AS tablename FROM table5
) AS XX GROUP BY id HAVING COUNT(id) > 1;
table2とtable5で1が重複しており、
table2とtable3とtable5で2が重複しているケースで実行してみました。
【動作確認のSQL】
WITH
table1 AS (
SELECT 10 id
),
table2 AS (
SELECT 1 id UNION ALL
SELECT 2 id UNION ALL
SELECT 20 id
),
table3 AS (
SELECT 2 id UNION ALL
SELECT 30 id
),
table4 AS (
SELECT 40 id
),
table5 AS (
SELECT 1 id UNION ALL
SELECT 2 id UNION ALL
SELECT 50 id
)
SELECT id FROM (
SELECT id, 'table1' AS tablename FROM table1
UNION ALL
SELECT id, 'table2' AS tablename FROM table2
UNION ALL
SELECT id, 'table3' AS tablename FROM table3
UNION ALL
SELECT id, 'table4' AS tablename FROM table4
UNION ALL
SELECT id, 'table5' AS tablename FROM table5
) AS XX GROUP BY id HAVING COUNT(*) > 1;
【動作確認結果】
id
----
1
2
(2 rows)