[英]MySQL select dates between with date functions and min max
Why does this return '2015-01-19'?: 为什么返回“ 2015-01-19” ?:
SELECT date
FROM hours
HAVING date BETWEEN DATE_SUB(max(date), INTERVAL 2 DAY) AND DATE_ADD(max(date), INTERVAL 1 DAY)
when this returns '2015-01-20' and '2015-01-19'?: 什么时候返回'2015-01-20'和'2015-01-19'?:
SELECT date
FROM hours
HAVING date BETWEEN '2015-01-18' AND '2015-01-21'
max date is '2015-01-20' and there are records on both '2015-01-20' and '2015-01-19'. 最长日期是“ 2015-01-20”,并且在“ 2015-01-20”和“ 2015-01-19”上都有记录。 date is a date field.
date是一个日期字段。
I think you'll find that date_sub
returns a full time stamp eg '2008-11-11 13:23:44.657' see http://www.w3schools.com/sql/func_date_sub.asp for more details. 我认为您会发现
date_sub
返回完整的时间戳,例如'2008-11-11 13:23:44.657'有关更多详细信息,请参见http://www.w3schools.com/sql/func_date_sub.asp 。
You'll want to use the extract
method or date_format
( DATE_FORMAT(date_time_var, '%Y-%m-%d')
) to get just the day, month and year as used in your between statement. 您将要使用
extract
方法或date_format
( DATE_FORMAT(date_time_var, '%Y-%m-%d')
)来获取之间的语句中使用的日,月和年。
Your first example contains aggregate functions. 您的第一个示例包含聚合函数。 HAVING typically requires a GROUP BY, because it's a means to filter groups.
HAVING通常需要GROUP BY,因为这是过滤组的一种方法。 So putting
GROUP BY date
before HAVING date
will get you both the 19th and 20th (for your first SQL statement). 因此,将
GROUP BY date
放在HAVING date
GROUP BY date
之前会使您同时获得19号和20号(对于您的第一个SQL语句)。
That's HAVING
behaviour. 这是
HAVING
行为。
HAVING
will group results in your first query because there is a grouping function MAX
in HAVING
clause. HAVING
意志集团导致你的第一个查询,因为有一组函数MAX
在HAVING
子句。 All returned rows will be grouped in one row-group because there is no GROUP BY
instruction. 因为没有
GROUP BY
指令,所以所有返回的行将被分组为一个行组。 Therefore, you only get one result. 因此,您只会得到一个结果。
date
value of this group can be any of the grouped rows. 该组的
date
值可以是任何分组的行。
HAVING
will do no group in second query because there is no grouping function in HAVING
clause, nor GROUP BY
instruction. HAVING
将不在第二个查询中进行分组,因为HAVING
子句中也没有分组功能,也没有GROUP BY
指令。
Adding a GROUP BY date
as suggested will group rows that have the same date
; 如建议的那样添加
GROUP BY date
将对具有相同date
行进行分组; hence MAX
will only return that date
value instead of MAX
of all dates. 因此
MAX
只会返回该date
值,而不是所有日期的MAX
。 So, you will retrieve all rows because MAX(date)
== date
in all grouped rows. 因此,您将检索所有行,因为所有分组行中的
MAX(date)
== date
。
SELECT `date`, GROUP_CONCAT(`date`), (SELECT MAX(`date`) FROM `hours`) AS `md`
FROM `hours`
GROUP BY `date`
HAVING `date`
BETWEEN DATE_SUB(md, INTERVAL 2 DAY) AND DATE_SUB(md, INTERVAL 1 DAY);
You might also use 您可能还会使用
SELECT `hours`.`date`, `md`.`d`
FROM `hours`, (SELECT MAX(`date`) AS `d` FROM `hours`) AS `md`
WHERE `hours`.`date`
BETWEEN DATE_SUB(`md`.`d`, INTERVAL 2 DAY) AND DATE_ADD(`md`.`d`, INTERVAL 1 DAY);
Not sure which one is the fastest... 不知道哪一个是最快的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.