[英]How can I merge data from two SQL tables?
我有兩張桌子。 表"alldates"
由稱為"nextdate"
的日期列組成。 表"availability"
由多個列組成,其中包括一個稱為"availdate"
的日期列。 表"alldates"
主鍵是"nextdate"
列。 "availability"
表主鍵是名為"event_num"
的列。
為了說明起見,假設表"alldates"
填充了16行,日期為10/01/2014 through 10/16/2014
,表"availability"
填充了9行,如下所示:
Availdate Event_num Event Description
10/01/2014 3 Joe's birthday
10/04/2014 12 Bill's dentist appt
10/04/2014 5 Buy pizza
10/05/2014 6 Clean the house
10/07/2014 7 Go to theater
10/07/2014 8 Continue forward
10/09/2014 9 Mow the grass
10/11/2014 10 Take a nap
10/15/2014 11 Fix the clock
我需要創建一個新表,如下所示:
Availdate Event_num Event Description
10/01/2014 3 Joe's birthday
10/02/2014 (from table "alldates")
10/03/2014 (from table "alldates")
10/04/2014 12 Bill's dentist appt
10/04/2014 5 Buy pizza
10/05/2014 6 Clean the house
10/06/2014 (from table "alldates")
10/07/2014 7 Go to theater
10/07/2014 8 Continue forward
10/08/2014 (from table "alldates")
10/09/2014 9 Mow the grass
10/10/2014 (from table "alldates")
10/11/2014 10 Take a nap
10/12/2014 (from table "alldates")
10/13/2014 (from table "alldates")
10/14/2014 (from table "alldates")
10/15/2014 11 Fix the clock
10/16/2014 (from table "alldates")
看起來像是經典的左加入我。
select a.nextdate as availdate,
b.event_num,
b.event_description
from alldates a
left join availability b
on a.nextdate = b.availdate
;
如果兩個表的列數相同,那么您可以在它們之間做一個UNION
並order by
Availdate
列進行Availdate
select * from
(
select Availdate,
Event_num,
Event Description
from alldates
UNION
select Availdate,
Event_num,
Event Description
from availability
) tab
order by Availdate
您想要的是LEFT OUTER JOIN
。 LEFT OUTER
告訴SQL包括第一個表中的行,即使它們在第二個表中沒有相應的條目也是如此。 “對應”由謂詞確定,該謂詞告訴數據庫一個表中的行與另一表中的行如何關聯。
以下查詢將從alldates
選擇所有行。 對於那些nextdate
行的匹配availdate
在availability
,每次將每一個匹配行顯示一次。 對於nextdate
與availability
不匹配的那些nextdate
,event_num和event_description將列為NULL
。
SELECT
alldates.nextdate,
availability.event_num,
availability.event_description
FROM
ALLDATES
LEFT JOIN availability
ON alldates.nextdate = availability.availdate;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.