0

我有许多表和一个公用表,其中包含所有这些表的 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
4

3 回答 3

1

如果您不想使用UNION ALL,可以像这样使用COALESCE相同的用法LEFT JOIN

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. 但是对于给定的数据结构,无论如何您都必须连接所有表。

于 2013-07-25T12:18:18.690 回答
0

您需要将所有表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

于 2013-07-25T11:49:11.583 回答
0

您可以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 演示

于 2013-07-25T12:12:01.847 回答