表名列出了所需的sql查询帮助

时间:2014-04-13 16:12:42

标签: sql

我有一个表Table_1,其中包含1到10的条目,我有20个其他表,它们在列中使用值1-10。 我想列出所有表名,其中包含缺少Table_1中相应条目的条目。

例如:

Table_1 has values 1- 10
Table_2 is using 2 and 5
Table_3 is using 7,9 and 28
Table_4 is using 2,7,9
Table_5 is using 7, 9,76

所以我的查询输出应该给我table_3和Table_5

2 个答案:

答案 0 :(得分:0)

以这种方式:

SELECT DISTINCT TableName
FROM (SELECT 'Table_2' as TableName, col
      FROM Table_2
      UNION ALL
      SELECT 'Table_3' as TableName, col
      FROM Table_3
      /*repeat for all tables*/
      UNION ALL
      SELECT 'Table_20' as TableName, col
      FROM Table_20) x
      LEFT JOIN Table_1 t ON x.col = t.col
WHERE t.col is NULL

答案 1 :(得分:0)

这应该有效。如果您使用的是sql server / Oracle,也可以使用减号和/或除集合运算符。不确定你正在使用什么数据库。

select 'in tbl 2 but not tbl 1' as which, numcol from table_2 where numcol not in (select numcol from table_1)
union all
select 'in tbl 3 but not tbl 1' as which, numcol from table_3 where numcol not in (select numcol from table_1)
union all
select 'in tbl 4 but not tbl 1' as which, numcol from table_4 where numcol not in (select numcol from table_1)
union all
select 'in tbl 5 but not tbl 1' as which, numcol from table_5 where numcol not in (select numcol from table_1)