繁体   English   中英

使用SQL Server 2005中的一个公用表从多个表中选择数据

[英]Select datas from multiple tables using one common table in sql server 2005

我有很多表和一个具有所有这些表的ID的公用表,例如:

表格1

| ID | VALUE |       DATE |
---------------------------
|  1 |   200 | 25/04/2013 |
|  2 |   250 | 26/05/2013 |

表2

| ID | VALUE |       DATE |
---------------------------
|  1 |   300 | 25/05/2013 |
|  2 |   100 | 12/02/2013 |

表3

| ID | VALUE |       DATE |
---------------------------
|  1 |   500 | 5/04/2013  |
|  2 |   100 | 1/01/2013  |

和一张普通桌子

| ID |  TABLE | TABLEID |
-------------------------
|  1 | table1 |       1 |
|  2 | table3 |       1 |
|  3 | table2 |       1 |
|  4 | table1 |       2 |
|  5 | table2 |       2 |
|  6 | table3 |       2 |

并使用此公用表,我需要选择以上3个表中的所有数据,例如:

output
id    table   tableid   value    date
1     table1  1         200      25/04/2013
2     table3  1         500      5/04/2013
3     table2  1         300      25/05/2013
4     table1  2         250      26/05/2013
5     table2  2         100      12/02/2013
6     table3  2         100      1/01/2013

如果您不想使用UNION ALL ,则可以使用LEFT JOINCOALESCE用作同一对象:

SELECT c.* 
     , COALESCE(t1.Value, t2.Value,t3.Value) AS Value
     , COALESCE(t1.Date, t2.Date,t3.Date) AS Date
  FROM Common c
  LEFT JOIN Table1 t1 ON c.tableid = t1.[id]
   AND [Table] = 'table1'
  LEFT JOIN Table2 t2 ON c.tableid = t2.[id]
   AND [Table] = 'table2'
  LEFT JOIN Table2 t3 ON c.tableid = t3.[id]
   AND [Table] = 'table3'
ORDER BY ID;

看到这个SQLFiddle

通过这种方式,您可以减少使用UNION ALL所有记录的任务。 但是对于给定的数据结构,无论如何都必须连接所有表。

您需要将所有表与common表分别连接,然后使用UNION ALL

SELECT *
  FROM Common c
  JOIN Table1 t1 ON c.tableid = t1.[id]
   AND [Table] = 'table1'
UNION ALL
SELECT *
  FROM Common c
  JOIN Table2 t2 ON c.tableid = t2.[id]
   AND [Table] = 'table2'
UNION ALL
SELECT *
  FROM Common c
  JOIN Table3 t3 ON c.tableid = t3.[id]
   AND [Table] = 'table3';

看到这个SQLFiddle

您可以在流程中将UNION ALL表添加标记列并统一,然后将结果与公用表联接。

WITH CTE_Tables AS 
(
   SELECT 'Table1' AS Tab, * FROM Table1
   UNION ALL
   SELECT 'Table2' AS Tab, * FROM Table2
   UNION ALL
   SELECT 'Table3' AS Tab, * FROM Table3
)
SELECT * 
FROM CommonTable c1 
LEFT JOIN CTE_Tables cte ON cte.ID = c1.TableID AND cte.Tab = c1.[Table]

SQLFiddle演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM