MySQL - 如何查找日期在开始日期到结束日期之间的记录
Posted
技术标签:
【中文标题】MySQL - 如何查找日期在开始日期到结束日期之间的记录【英文标题】:MySQL - How to find records which date is between start date to end date 【发布时间】:2015-10-31 17:17:01 【问题描述】:我有两个表并试图查找 start_date 和 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
现在我想从campaign
表中查找campaign_id=1
和created_date
介于created_date
到end_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
我已经编写了非常基本的选择查询来从 campaign
表中找到 start_date
和 end_date
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
但现在我不知道如何从created_date
位于start_date
和end_date
上方的statistic
表中查找记录
希望你能理解。我不擅长 mysql,因为我刚刚开始学习,所以如果可能的话,我需要帮助 :)
谢谢。
【问题讨论】:
【参考方案1】:试试这个:
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
【讨论】:
【参考方案2】:试试这个方法
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
【讨论】:
【参考方案3】:试试这个:
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。
【讨论】:
以上是关于MySQL - 如何查找日期在开始日期到结束日期之间的记录的主要内容,如果未能解决你的问题,请参考以下文章