按年度最快的选择方式?

时间:2016-03-29 04:00:37

标签: mysql

根据this comment,至少有8种不同的方式按年和月选择记录:

  1. 其中日期类似于' 2005-01 - %'
  2. 其中DATE_FORMAT(日期,'%Y-%m')=' 2005-01'
  3. 其中EXTRACT(YEAR_MONTH FROM date)=' 200501'
  4. 其中YEAR(日期)=' 2005'和MONTH(日期)=' 1'
  5. 其中substring(date,1,7)=' 2005-01'
  6. 其中日期介于2005-01-01'和' 2005-01-31'
  7. 其中日期> =' 2005-01-01'和日期< =' 2005-01-31'
  8. 其中日期为IN(' 2005-01-01',' 2005-01-02',' 2005-01-03',' 2005-01-04',' 2005-01-05',' 2005-01-06',' 2005-01-07',&# 39; 2005-01-08',' 2005-01-09',' 2005-01-10',' 2005-01-11', ' 2005-01-12',' 2005-01-13',' 2005-01-14',' 2005-01-15&#39 ;,' 2005-01-16',' 2005-01-17',' 2005-01-18',' 2005-01-19& #39;,' 2005-01-20',' 2005-01-21',' 2005-01-22',' 2005-01 -23',' 2005-01-24',' 2005-01-25',' 2005-01-26',' 2005 -01-27',' 2005-01-28',' 2005-01-29',' 2005-01-30',&#39 ; 2005-01-31&#39)
  9. 哪个是 WHERE 子句中最快的?哪个 GROUP BY 最快?他们中的任何一个都可以利用索引吗?

    我的特定查询如下:

    select count(*) 
    from quotes quote
    where EXTRACT(YEAR_MONTH FROM qtime) = :date
    

    qtimeTIMESTAMP

    但我还需要获得最多报价的月份:

    select date_format(qtime,'%Y-%m') d,count(*) c
    from quotes
    group by EXTRACT(YEAR_MONTH FROM qtime)
    order by c desc, qid asc limit 1;
    

    在这种情况下,我无法使用比较运算符。

1 个答案:

答案 0 :(得分:6)

我分析了所有这些查询并得到了结果。

between => Showing rows 0 - 29 (158 total, Query took 0.0030 sec)

like => Showing rows 0 - 29 (167 total, Query took 0.0031 sec)

DATE_FORMAT => Showing rows 0 - 29 (167 total, Query took 0.0237 sec)

EXTRACT => Showing rows 0 - 29 (167 total, Query took 0.0031 sec)

YEAR, MONTH => Showing rows 0 - 29 (167 total, Query took 0.0187 sec)

substr => Showing rows 0 - 29 (167 total, Query took 0.0224 sec)

> < => Showing rows 0 - 29 (158 total, Query took 0.0030 sec)

所以我可以说中间的使用是最好的,而且速度更快。虽然使用大于和小于是相同的结果,但我认为介于两者之间非常聪明。