[英]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.