SELECT row by DATEPART()

我与影子孤独终老i 提交于 2019-11-26 17:14:37

问题


I need to get rows from the database where the records are of one month. I tried this SELECT:

$result = mysql_query("SELECT * FROM my_table WHERE DATEPART('month', date_column)=11");

In database is a lot of rows that have a date in the 11. month, but i do not get any results. Can anyone help me? Thank!


回答1:


There is no DATEPART function in MySQL. Use MONTH(date_column) or EXTRACT(MONTH FROM date_column) instead.




回答2:


    SELECT * FROM my_table WHERE MONTH(date_column)=11



回答3:


If you have an index on date_column and you concern about performance it is better to NOT apply functions over the column. (Be aware that this solution, do not anwsers exactly what you asked, becouse it also involves the year)

-- For mysql specific:
SELECT * FROM my_table
WHERE date_column >= '2012-11-01' 
  and date_column < '2012-11-01' + INTERVAL 1 MONTH

(mysql fiddle)

-- For tsql specific:
SELECT * FROM my_table
WHERE date_column >= '2012-11-01'
  and date_column < DATEADD(month,1,'2012-11-01')

(tsql fiddle)




回答4:


If your DATEPART is not working in MYSQL then you can use:

SELECT * FROM MyTable WHERE MONTH(joinningDate)=MONTH(NOW())-1 and YEAR(joinningDate)=YEAR(NOW());

It will return all records who have inserted in MyTable in last month.



来源:https://stackoverflow.com/questions/13402012/select-row-by-datepart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!