简体   繁体   English

是否有另一种更好的方法可以使用php以此在SQL中按年过滤?

[英]Is there another and better way to filter by years in SQL using php of this?

I have this code to filter by years. 我有这段代码可以按年过滤。 It's working, but I want to know if there is another way to do it. 它正在工作,但是我想知道是否还有另一种方法。

This is my code : 这是我的代码:

$filter_values = '2012,2019,2018';

// sql query
$query = "SELECT * FROM `mytable` WHERE ";

// convert string to array
$str_arr = explode(",", $filter_values);

// check if is first loop
$first = true;

// loop to create SQL query filter
foreach ($str_arr as $row) {
    if ($first == true) {
        $query .= " (`date` LIKE '" . $row .= "' ";
    } else {
        $query .= " OR `date` LIKE '" . $row .= "' ";
    }

    $first = false;
}

$query .= ")";

The final SQL query will be like this: 最终的SQL查询将如下所示:

SELECT * 
FROM `mytable` 
WHERE (`date` LIKE '2012' 
       OR `date` LIKE '2019' 
       OR `date` LIKE '2018')

Do not use like for dates. 不要在日期中使用like like is an operation on strings, not date. like对字符串的操作,而不是日期。

One simple method is to use year() and in : 一种简单的方法是使用year()in

where year(date) in (2012, 2019, . . . )

You are selecting a lot of data, so it probably not important that this cannot use an index. 您正在选择大量数据,因此不要使用索引可能并不重要。 In other circumstances, ranges are better: 在其他情况下,范围更好:

where (date >= '2012-01-01' and date < '2013-01-01') or
      (date >= '2019-01-01' and date < '2020-01-01') or
      . . .

because this formula could use an index if available. 因为此公式可以使用索引(如果有)。

Simple. 简单。

$sql = "SELECT * FROM mytable where date BETWEEN ($from , $to)"


$from & $To are your dates variables. $ from和$ To是您的日期变量。

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

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