简体   繁体   English

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

[英]How to merge more than two (3) tables in SQL

In a Facebook-like notification system I have three tables, like this.... 在类似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 |
|____|___________|_____________|

To return all these data in one row, I used SQL union... 为了将所有这些数据返回一行,我使用了SQL联合...

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

...but it brings it all together in one column. ...但是它将所有内容汇总到一栏中。 Instead of that, I need the result to be in a table like this, in order of Timestamp 取而代之的是,我需要将结果按时间戳记放在这样的表

________________________________________________________
| 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 |
|____|___________|___________|___________|_____________|

Is it possible to do, only with SQL without handing over the job to the PHP engine? 是否可以仅使用SQL而不将工作移交给PHP引擎? Any ideas appreciated. 任何想法表示赞赏。

You can do this using union all and order by : 您可以使用union all并按以下order 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;

Note that union all is more efficient than union because it does not return duplicates. 请注意, union allunion效率更高,因为它不返回重复项。

You need to add dummy columns in each part of the union: 您需要在联合的每个部分中添加虚拟列:

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

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

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