SQL使用SELECT只选择几行

时间:2015-07-14 19:48:32

标签: mysql sql

到目前为止,这是我的代码:

DATEADD(month, SpecialDays.BirthdayMonth, @start_date)          as birthday_month,
Present.typeOfPresent                                           as birthday_present
DATEADD(month, SpecialDays.ChristmasMonth, @start_date)         as christmas_month,
Present.typeOfPresent                                           as christmas_present

当前表包含12个不同的月份(采用DATEADD格式),每个月对应一个不同的礼物来获取某人。

我希望Present表中的birthday_present对应于month_month月份中列出的礼物,对于christmas_present也是如此。在伪代码中,类似于:

DATEADD(month, SpecialDays.BirthdayMonth, @start_date)          as birthday_month,
Present.typeOfPresent WHERE Present.month=DATEADD(month, SpecialDays.BirthdayMonth, @start_date)                                        as birthday_present
DATEADD(month, SpecialDays.ChristmasMonth, @start_date)         as christmas_month,
Present.typeOfPresent WHERE Present.month=DATEADD(month, SpecialDays.ChristmasMonth, @start_date)                                           as christmas_present

1 个答案:

答案 0 :(得分:0)

Present

使用两个连接
SELECT p1.month          as birthday_month,
        p1.typeOfPresent as birthday_present
        p2.month         as christmas_month,
        p2.typeOfPresent as christmas_present
FROM SpecialDays AS s
JOIN Present AS p1 ON p1.month = DATEADD(month, SpecialDays.BirthdayMonth, @start_date) 
JOIN Present AS p2 ON p2.month = DATEADD(month, SpecialDays.ChristmasMonth, @start_date)