SQL Query具有相同列的多个表

时间:2012-08-09 15:41:08

标签: sql sql-server-2008

我有15个表,它们都有CreationDate和LastModifiedDate列,可以查询所有表并在表中查找空值。

这就是我想我必须做的事,但想知道是否有更有效的方式或更简单的方法来做以下事情

Select COUNT(*) FROM Table1, Table2, Table3
WHERE table1.CreationDate IS NULL
      OR table1.LastModifiedDate IS NULL
      OR table2.CreationDate IS NULL
      OR table2.LastModifiedDate IS NULL
      OR table3.CreationDate IS NULL
      OR table3.LastModifiedDate IS NULL

2 个答案:

答案 0 :(得分:3)

select count(*)
from (
    select CreationDate, LastModifiedDate from Table1
    union all
    select CreationDate, LastModifiedDate from Table2
    union all
    select CreationDate, LastModifiedDate from Table3
) a 
where CreationDate is null or LastModifiedDate is null

答案 1 :(得分:0)

您原始查询没有达到预期效果。它在具有缺失值的所有行之间进行交叉连接。这可能导致大量数据(如果所有表都有多行)或者根本没有(如果没有丢失的行)。

我假设您想知道丢失内容的表名:

select tablename, count(*),
       sum(case when CreationDate is null then 1 else 0 end) as MissingCreationDate,
       sum(case when LastModifiedDate is null then 1 else 0 end) as MissingLastModifiedDate
from ((select 'table1' as tablename,  CreationDate, LastModifiedDate
       from Table1 
      ) union all
      (select 'table2' as tablename, CreationDate, LastModifiedDate
       from Table2
      ) union all
      . . .
      (select 'table15', CreationDate, LastModifiedDate
       from Table3
      ) 
     ) t
where CreationDate is null or LastModifiedDate is null
group by tablename