如何从 mysql 中的日期获取月份
我希望能够使用这样的语句从 mysql 获取结果:
SELECT *
FROM table
WHERE amount > 1000
但是我想获取限制在某个月份和年份的结果(基于用户的输入)...我正在尝试这样:
SELECT *
FROM table
WHERE amount > 1000
AND dateStart = MONTH('$m')
... $m
是一个月,但它给出了错误。
在该表中,它实际上有两个日期:startDate
和 endDate
,但我重点关注 startDate
。输入值可以是月份和年份。如何表达根据当年该月获取结果的 SQL 语句?
I want to be able to fetch results from mysql with a statement like this:
SELECT *
FROM table
WHERE amount > 1000
But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:
SELECT *
FROM table
WHERE amount > 1000
AND dateStart = MONTH('$m')
...$m
being a month but it gave error.
In that table, it actually have two dates: startDate
and endDate
but I am focusing on startDate
. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您很接近 - 向后进行比较(假设
startDate
是 DATETIME 或 TIMESTAMP 数据类型):注意事项:
替代方案:
因为对列使用函数不能使用索引,所以更好的方法是使用
BETWEEN
和STR_TO_DATE
函数:请参阅格式化语法文档。
参考:
You were close - got the comparison backwards (assuming
startDate
is a DATETIME or TIMESTAMP data type):Caveats:
Alternatives:
Because using functions on columns can't use indexes, a better approach would be to use
BETWEEN
and theSTR_TO_DATE
functions:See the documentation for formatting syntax.
Reference:
使用
month()
函数。Use the
month()
function.试试这个:
Try this:
例如,
这将创建一个查询,例如
+ Interval 1 Month
是 date_add()。SELECT Date('2010-01-01'+间隔1个月)
->2010-02-01
SELECT Date('2010-12-01'+间隔1个月)
->2011-01-01
这样您始终可以获得下个月的第一天。您想要的记录的 dateStart 必须早于该日期,但晚于/等于您传递给 sprintf() 的月份(和年份)的第一天。
'2010-01-01'+Interval 1 Month
在行之间不会更改。 MySQL 只会计算该术语一次,并且可以利用索引进行搜索。E.g.
This will create a query like e.g.
+ Interval 1 month
is an alternative to date_add().SELECT Date('2010-01-01'+Interval 1 month)
->2010-02-01
SELECT Date('2010-12-01'+Interval 1 month)
->2011-01-01
This way you always get the first day of the following month. The records you want must have a dateStart before that date but after/equal to the first day of the month (and year) you've passed to sprintf().
'2010-01-01'+Interval 1 month
doesn't change between rows. MySQL will calculate the term only once and can utilize indices for the search.试试这个
Try this
如果(日期字段是文本,然后将此字符串转换为日期),请尝试以下操作:
Try this if(date field is text then convert this string to date):
适用于:MySQL 5.7、MySQL 5.6、MySQL 5.5、MySQL 5.1、MySQL 5.0、MySQL 4.1、MySQL 4.0、MySQL 3.23
日:
月:
年份:
Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23
Day:
Month:
Year: