简体   繁体   English

在$ sql查询中使用date()进行过滤

[英]Filter with date() on $sql query

I'm having problems understanding where to place the conversion to take the unixtime and convert it to the specific month and year. 我在理解将转换转换为unixtime并将其转换为特定月份和年份的位置时遇到了问题。

$sql = "SELECT * FROM logs WHERE clientid = '5604' AND timestamp = 'Jan 13' ";

Where would I need to place the date() function to filter the timestamp to month and year specified? 我需要在哪里放置date()函数以将时间戳过滤为指定的月份和年份?

First of all, date litterals in MySQL must follow one of the below formats: 首先,MySQL中的日期垃圾必须遵循以下格式之一:

  • YY*MM*DD YY * MM * DD
  • YYYY*MM*DD YYYY * MM * DD

* means "any non-digit non-alphanumeric character or no character at all". *表示“任何 非数字 非字母数字字符或完全没有字符”。

YY or YYYY is the year with two or four digits. YYYYYY是具有两位或四位数的年份。

MM and DD are the month and day numbers. MMDD是月份和日期。

Then, if you want to get results for a specific date, you can do something like this: 然后,如果要获取特定日期的结果,可以执行以下操作:

... WHERE DATE(timestamp_field) = '2013-01-13';

But actually this query wouldn't be able to use an index on timestamp_field . 但是实际上,此查询无法使用timestamp_field上的索引。 This approach is better because and index on timestamp_field could be used: 这种方法更好,因为可以使用timestamp_field index:

... WHERE timestamp_field >= '2013-01-13' AND timestamp_field < '2013-01-14';

Create two variables. 创建两个变量。 Make 1 equal to the 1st day of the year month you want and the 2nd equal to the 1st day of the following year month. 使1等于所需的年份月份的第一天,使第二等于下一年月份的第一天。 Then it's simply this: 然后就是这样:

where timestamp >= your first variable
and timestamp < your second variable

This approach will handle the time component of your timestamp field and will perform faster than if you try to use functions. 这种方法将处理您的时间戳字段的时间部分,并且比您尝试使用函数的执行速度更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM