MySQL - 如何查找日期在开始日期到结束日期之间的记录

时间:2015-10-31 17:17:02

标签: mysql sql date

我有两张桌子,试图找到start_date和amp;之间的记录。 END_DATE。

广告系列表

campaign_id     campaign_name       start_date              end_date
***********     *************       **********              ********
1               Deacon Navarro      2015-10-28 00:00:00     2015-10-31 00:00:00
2               Emily Oliver        2015-10-29 00:00:00     2015-11-04 00:00:00

统计表

id  campaign_id     comments    likes       created_date
**  ***********     ********    *****       ************
1   1               14          24          2015-10-28 00:00:00
2   1               34          12          2015-10-29 00:00:00
3   1               23          12          2015-10-30 00:00:00
4   1               23          24          2015-10-31 00:00:00
5   1               21          45          2015-11-01 00:00:00
6   2               12          17          2015-10-31 00:00:00
7   2               23          12          2015-11-01 00:00:00

现在,我想查找statistic表中campaign_id=1created_date位于created_dateend_date campaign表之间的所有记录。

我需要这个输出:

1   1               14          24          2015-10-28 00:00:00
2   1               34          12          2015-10-29 00:00:00
3   1               23          12          2015-10-30 00:00:00
4   1               23          24          2015-10-31 00:00:00

我写了非常基本的选择查询来查找start_date&来自end_date

campaign
SELECT start_date, end_date FROM campaign WHERE campaign_id = '1' 

我得到了这个结果:

start_date              end_date
**********              ********
2015-10-28 00:00:00     2015-10-31 00:00:00

但现在我不知道如何查找statistic表中created_date位于start_date之上的记录。 end_date

希望你明白。我对MySQL不好,因为我只是盯着学习所以我需要帮助如果可能的话:):

感谢。

3 个答案:

答案 0 :(得分:0)

试试这个:

  SELECT statistic.* 
  FROM statistic, campaign
  WHERE
  campaign.campaign_id = '1'
  AND campaign.campaign_id = statistic.campaign_id
  AND statistic.created_date BETWEEN campaign.start_date AND campaign.end_date

答案 1 :(得分:0)

试试这种方式

SELECT statistic.* 
FROM statistic
INNER JOIN campaign ON statistic.campaign_id= campaign.campaign_id;
WHERE statistic.created_date BETWEEN campaign.start_date AND campaign.end_date

答案 2 :(得分:0)

试试这个:

SELECT s.* 
FROM statistic AS s
INNER JOIN campaign AS c ON s.campaign_id = c.campaign_id;
WHERE c.campaign_id = 1
AND s.created_date BETWEEN c.start_date AND c.end_date

有关JOIN语法here的更多信息。