按日 and/or 月 and/or 年检索记录的最有效方法是什么?

What is the most efficient way to retrieve records by day and/or month and/or year?

select按天and/or月and/or年记录的最有效方法是什么?

INT(2) day
INT(2) month
INT(4) year

SELECT * FROM table WHERE table.year=2015
SELECT * FROM table WHERE table.month=9 AND table.year=2015
SELECT * FROM table WHERE table.day=26 AND table.month=9 AND table.year=2015

DATE   date

SELECT * FROM table WHERE YEAR(table.date)=2015
SELECT * FROM table WHERE MONTH(table.date)=9 AND YEAR(table.date)=2015
SELECT * FROM table WHERE table.date="2015-09-26"

Note: There also may be situations where the day is searched regardless of the month and year, or the month is search regardless of the day and year.

效率更高的方法是第一种方法。 但是您应该使用本机日期格式,这样就排除了第一种方法。

所以,最好的方法是:

select * from table where table.date >= '2015-01-01' and table.date < '2016-01-01';
select * from table where table.date >= '2015-09-01' and table.date < '2015-10-01';
select * from table where table.date >= '2015-09-26' and table.date < '2016-09-27';

最后一个条件可能可以使用 =,如果日期没有时间部分。

第一个可以根据索引或组合(注意复数)进行拖动。很可能在试图变得聪明时,它会变慢。复合宽度并不完全比日期数据类型的大小更精简,日期数据类型的大小全部以 @3 字节为单位。

除非您的查询是 "give me the first day of every month regardless of year and month"

因此,我在性能方面排名第二。您不仅需要根据上述查询来判断性能,还需要根据整体性能(考虑需要过多的复合材料及其宽度,即使相对较薄)对 inserts/updates.

的影响

但即便如此,即使只关注您的查询,3 个字节也小于 8 个(或大多数人可能使用的 12 个)。请注意,我们说的是 Date,而不是 Datetime

此外,您无需编写自己的函数即可获得日期函数的所有好处。