如何合并两个SQL表中的数据?

时间:2014-11-19 23:25:06

标签: mysql

我有两张桌子。表"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")

3 个答案:

答案 0 :(得分:1)

看起来像是经典的左派加入我。

select a.nextdate as availdate,
b.event_num,
b.event_description
from alldates a
left join availability b
on a.nextdate = b.availdate
;

答案 1 :(得分:0)

如果表格的列数相同,那么您可以在它们与UNION order by列之间Availdate进行select * from ( select Availdate, Event_num, Event Description from alldates UNION select Availdate, Event_num, Event Description from availability ) tab order by Availdate

{{1}}

答案 2 :(得分:0)

你想要的是LEFT OUTER JOINLEFT OUTER告诉SQL包含第一个表中的行,即使它们在第二个表中没有相应的条目。 “对应”由谓词决定,这是告诉数据库一个表中的行如何与另一个表中的行相关联的条件。

以下查询将从alldates中选择所有行。对于nextdateavaildate中的行availability匹配的用户,每个匹配行将显示一次。对于nextdateavailability不匹配的人,event_num和event_description将列为NULL

SELECT
    alldates.nextdate,
    availability.event_num,
    availability.event_description
FROM
    ALLDATES
    LEFT JOIN availability
ON alldates.nextdate = availability.availdate;