如何在SQL中合并两(3)个表

时间:2014-09-21 17:20:59

标签: php mysql sql sql-server

在类似Facebook的通知系统中,我有三张桌子,就像这样......

table1

________________________________
| id |  value_1  |  timestamp  |
|----|-----------|-------------|
| id |  value21  |  2014-05-21 |
| id |  value22  |  2014-05-22 |
|____|___________|_____________|

table2

________________________________
| id |  value_2  |  timestamp  |
|----|-----------|-------------|
| id |  value30  |  2014-05-30 |
|____|___________|_____________|

table3

________________________________
| id |  value_3  |  timestamp  |
|----|-----------|-------------|
| id |  value01  |  2014-05-01 |
| id |  value27  |  2014-05-27 |
|____|___________|_____________|

要在一行中返回所有这些数据,我使用了SQL union ...

(SELECT value_1  FROM table1)
UNION
(SELECT value_2  FROM table2)
UNION
(SELECT value_3  FROM table3)

......但它将所有内容整合在一栏中。而不是那样,我需要将结果放在这样的表中, 按时间戳顺序

________________________________________________________
| id |  value_1  |  value_2  |  value_3  |  timestamp  |
|----|-----------|-----------|-----------|-------------|
| id |  null     |  null     |  value01  |  2014-05-01 |
| id |  value21  |  null     |  null     |  2014-05-21 |
| id |  value22  |  null     |  null     |  2014-05-22 |
| id |  null     |  null     |  value27  |  2014-05-27 |
| id |  null     |  value30  |  null     |  2014-05-30 |
|____|___________|___________|___________|_____________|

是否可以使用SQL而不将作业移交给PHP引擎? 任何想法都赞赏。

2 个答案:

答案 0 :(得分:3)

您可以使用union allorder by

执行此操作
SELECT id, value_1, NULL as value_2, NULL as value_3, timestamp
FROM table1
UNION ALL
SELECT id, NULL, value_2, NULL, timestamp
FROM table2
UNION ALL
SELECT id, NULL, NULL, value_3, timestamp
FROM table3
ORDER BY timestamp;

请注意,union allunion更有效,因为它不会返回重复项。

答案 1 :(得分:1)

您需要在联合的每个部分添加虚拟列:

SELECT value_1
     , cast(null as <type_of_value2>) as value_2
     , cast(null as <type_of_value3>) as value_3
     , ts 
FROM table1 
UNION 
SELECT cast(null as <type_of_value1>) as value_1
     , value_2
     , cast(null as <type_of_value3>) as value_3 
     , ts
FROM table2 
UNION 
SELECT cast(null as <type_of_value1>) as value_1
     , cast(null as <type_of_value2>) as value_2
     , value_3
     , ts 
FROM table3
ORDER BY ts