从四个表中的任何一个中选择数据

时间:2018-08-07 08:52:53

标签: sql sql-server sql-server-2008

我想从四个表中的任何一个中选择数据。数据可以是四分之一中的任何一个。四张表也将有数据。两个表也将有数据。一个表也将有数据。请在下面纠正我。

select top 100  t1.* 
from  
Table1 t1 
left JOIN Table2 t2 on t1.EventId = t2.EventId 
LEFT JOIN Table3 t3 ON t1.EventId = t3.EventId
LEFT JOIN Table4 t4 ON t1.EventId = t4.EventId
WHERE 
t1.EventId = 12345 AND 
t1.EditType = 'D' and 
t2.EditType = 'D'and 
t3.EditType = 'D' and 
t4.EditType = 'D'

2 个答案:

答案 0 :(得分:3)

WHERE子句中放入条件会将外部联接转换为内部联接。将条件放入ON子句

Select *
from Table1 t1 
left JOIN Table2 t2 
  on t1.EventId = t2.EventId 
  and t2.EditType = 'D'
left  JOIN Table3 t3 
  ON t1.EventId = t3.EventId
  and t3.EditType = 'D' 
left  JOIN Table4 t4 
  ON t1.EventId = t4.EventId
  and t4.EditType = 'D'

where t1.EventId = 12345
and t1.EditType = 'D' 

答案 1 :(得分:2)

如果表具有相同的结构,则最好在视图或CTE(公用表表达式)中全部合并,然后从中选择而不是进行左联接-这样,您的信息就会显示在单独的记录中:

WITH FullData AS (
SELECT *, 1 AS TableSource FROM Table1
UNION ALL
SELECT *, 2 AS TableSource FROM Table2
UNION ALL
SELECT *, 3 AS TableSource FROM Table3
UNION ALL
SELECT *, 4 AS TableSource FROM Table4 )
SELECT * FROM FullData WHERE EventID = 12345 And EventType = 'D'

根据我的示例,您还可以添加一个源标识符,以告知要从中提取信息的表-只要结构在整个过程中都保持不变,则所有并集都可以正常工作。