sql查询从数据库中查找缺少的表

时间:2012-05-03 11:23:04

标签: sql database oracle

我正在使用ORACLE数据库。 的修改

我只想要列表中没有的表,而不是数据库中的所有表。

例如:在我的数据库中,存在以下表格:

a
b
c
d
e
r
s

我收到了一份表格清单:

a
b
c
v
h

我希望在我的数据库中找出哪些表缺席(不存在)

所以:a,b,c是我的数据库中存在的那些表。所以不包括这些表我的答案是:

v and h 

我的答案不是d,e,r,s

我如何编写查询以查找?

5 个答案:

答案 0 :(得分:2)

您可以使用

SELECT a.table_name FROM (SELECT 'A' as table_name 
               FROM DUAL UNION
               SELECT 'B' as table_name 
               FROM DUAL UNION
               SELECT 'C' as table_name 
               FROM DUAL UNION
               SELECT 'V' as table_name 
               FROM DUAL UNION
               SELECT 'H' as table_name 
               FROM DUAL) a WHERE NOT EXISTS (
SELECT 1 FROM DBA_TABLES b where b.table_name=a.table_name)

答案 1 :(得分:1)

WITH table_names AS ( 
   SELECT 'A' AS tname FROM DUAL
   UNION ALL
   SELECT 'B' FROM DUAL
   UNION ALL
   SELECT 'C' FROM DUAL
   UNION ALL
   SELECT 'D' FROM DUAL
   UNION ALL
   SELECT 'E' FROM DUAL
)
SELECT tn.tname
FROM table_name tn
WHERE NOT EXISTS (SELECT 1  
                  FROM all_tables at
                  WHERE tn.tname = at.table_name);

WITH部分只是编写派生表(“内联视图”)的另一种(可重用)方式。

答案 2 :(得分:1)

我会使用MINUS运算符(摘要如下):

select table_name from table_list
minus
select table_name from db_tables
;

更全面:

with table_list as 
(     select 'A' table_name from dual    
union select 'B' table_name from dual
union select 'C' table_name from dual
union select 'V' table_name from dual
union select 'H' table_name from dual
) 
, db_tables as
(     select 'A' table_name from dual
union select 'B' table_name from dual
union select 'C' table_name from dual
union select 'D' table_name from dual
union select 'E' table_name from dual
union select 'R' table_name from dual
union select 'S' table_name from dual
)
select table_name from table_list
minus
select table_name from db_tables
;

答案 3 :(得分:0)

SELECT table_name FROM DBA_tables WHERE table_name IN (Yourlist comes here)

例如

SELECT table_name FROM DBA_tables WHERE table_name NOT IN ('a','b','c');

答案 4 :(得分:0)

您可以使用表格和sys.dbms_debug_vc2coll从列表中创建虚拟列。

以下应该可以解决问题:

SELECT
    column_value AS missing_table_names
FROM
    TABLE(SYS.DBMS_DEBUG_VC2COLL('a','b','c','v','h'))
WHERE
    column_value NOT IN (
        SELECT
            table_name
        FROM
            ALL_TABLES
    );