[英]MySQL BETWEEN DATE RANGE
I have a scenario where I need to pull up delivery dates based on a table below (Example) 我有一个场景,我需要根据下表提取交货日期(示例)
job_id | delivery_date
1 | 2013-01-12
2 | 2013-01-25
3 | 2013-02-15
What I'm trying to do is show the user all the delivery dates that start with the earliest (in this case it would be 2013-01-12) and add an another 21 days to that. 我要做的是向用户显示最早开始的所有交付日期(在这种情况下,它将是2013-01-12)并再添加21天。 Basically, the output I would expect it to show of course, the earliest date being the starting date 2013-01-12 and 2013-01-25. 基本上,我希望它显示的输出当然,最早的日期是2013-01-12和2013-01-25的开始日期。 The dates past the February date are of no importance since they're not in my 21 date range. 2月份之后的日期并不重要,因为它们不在我的21日期范围内。 If it were a 5 day range, for example, then of course 2013-01-25 would not be included and only the earliest date would appear. 例如,如果它是5天范围,那么当然不包括2013-01-25,只会出现最早的日期。
Here is main SQL clause I have which only shows jobs starting this year forward: 这是我的主要SQL条款,它只显示今年开始的工作:
SELECT date, delivery_date
FROM `job_sheet`
WHERE print_status IS NULL
AND job_sheet.date>'2013-01-01'
Is it possible to accomplish this with 1 SQL query, or must I go with a mix of PHP as well? 是否可以通过1个SQL查询完成此操作,或者我是否也必须使用PHP的混合?
SELECT date,
delivery_date
FROM job_sheet
WHERE print_status IS NULL
AND job_sheet.date BETWEEN (SELECT MIN(date) FROM job_sheet) AND
(SELECT MIN(date) FROM job_sheet) + INTERVAL 21 DAY
You can use the following: 您可以使用以下内容:
select *
from job_sheet
where print_status IS NULL
and delivery_date >= (select min(delivery_date)
from job_sheet)
and delivery_date <= (select date_add(min(delivery_date), interval 21 day)
from job_sheet)
See SQL Fiddle with Demo 请参阅SQL Fiddle with Demo
If you are worried about the dates not being correct, if you use a query then it might be best to pass in the start date to your query, then add 21 days to get the end date. 如果您担心日期不正确,如果您使用查询,那么最好将开始日期传递给您的查询,然后添加21天以获取结束日期。 Similar to this: 与此类似:
set @a='2013-01-01';
select *
from job_sheet
where delivery_date >= @a
and delivery_date <= date_add(@a, interval 21 day)
SELECT j.job_id
, j.delivery_date
FROM `job_sheet` j
JOIN ( SELECT MIN(d.delivery_date) AS earliest_date
FROM `job_sheet` d
WHERE d.delivery_date >= '2013-01-01'
) e
ON j.delivery_date >= e.earliest_date
AND j.delivery_date < DATE_ADD(e.earliest_date, INTERVAL 22 DAY)
AND j.print_status IS NULL
ORDER BY j.delivery_date
(The original query has a predicate on job_sheet.date
; the query above references the d.delivery_date
... change that if it is supposed to be referencing the date
column instaed.) (原始查询在job_sheet.date
上有一个谓词;上面的查询引用了d.delivery_date
...如果它应该引用实例化的date
列,则更改它。)
If the intent is to only show delivery_date
values from today forward, then change the literal '2013-01-01'
to an expression that returns the current date, eg DATE(NOW())
如果意图仅显示今天的delivery_date
值,则将文字'2013-01-01'
更改为返回当前日期的表达式,例如DATE(NOW())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.