gpt4 book ai didi

sql-server - 从 3 个表中查询所有数据的最快方法

转载 作者:行者123 更新时间:2023-12-04 01:37:18 25 4
gpt4 key购买 nike

假设我有 3 个这样的表:

表 1

|Id|Date |Data1|
|--|---- |-----|
|1 |24/05|Some1|

表 2

|Id|Date |Data2|
|--|---- |-----|
|1 |24/05|Some2|
|1 |12/06|Some2|

表 3

|Id|Date |Data3|
|--|---- |-----|
|1 |24/05|Some3|
|1 |14/06|Some3|

我怎样才能得到这样的结果:

|Id|Date |Data1|Data2|Data3|
|--|-----|-----|-----|-----|
|1 |24/05|Some1|Some2|Some3|
|1 |12/06|NULL |Some2|NULL |
|1 |14/06|NULL |NULL |Some3|

使用 MS SQL。

我想到的是

SELECT Id, Date, Data1, Data2, Data3 FROM Table1 
LEFT JOIN Table2 ON Table1.Id = Table2.Id AND Table1.Date = Table2.Date
LEFT JOIN Table3 ON Table1.Id = Table3.Id AND Table1.Date = Table3.Date
UNION
SELECT Id, Date, Data1, Data2, Data3 FROM Table2
LEFT JOIN Table1 ON Table2.Id = Table1.Id AND Table2.Date = Table1.Date
LEFT JOIN Table3 ON Table2.Id = Table3.Id AND Table2.Date = Table3.Date
UNION
SELECT Id, Date, Data1, Data2, Data3 FROM Table3
LEFT JOIN Table1 ON Table3.Id = Table1.Id AND Table3.Date = Table3.Date
LEFT JOIN Table2 ON Table3.Id = Table2.Id AND Table3.Date = Table2.Date

有没有更好的方式查询数据?

最佳答案

select 
id = coalesce(t1.id,t2.id,t3.id)
, [date] = coalesce(t1.[date],t2.[date],t3.[date])
, t1.Data1
, t2.Data2
, t3.Data3
from Table1 t1
full join Table2 t2
on t1.id = t2.id
and t1.[date]=t2.[date]
full join Table3 t3
on (t1.id = t3.id and t1.[date]=t3.[date])
or (t2.id = t3.id and t2.[date]=t3.[date])

rextester 演示:http://rextester.com/ATCJ12705

返回:

+----+-------+-------+-------+-------+
| id | date | Data1 | Data2 | Data3 |
+----+-------+-------+-------+-------+
| 1 | 24/05 | Some1 | Some2 | Some3 |
| 1 | 12/06 | NULL | Some2 | NULL |
| 1 | 14/06 | NULL | NULL | Some3 |
+----+-------+-------+-------+-------+

关于sql-server - 从 3 个表中查询所有数据的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44500749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com