简体   繁体   English

从数据库选择带日期时间

[英]Select with datetime from database

I have a problem with my select : I have a form with 2 text boxes : date_min and date_max. 我的选择出现问题:我有一个包含2个文本框的表单:date_min和date_max。 This dates come in controller : 这个日期在控制器中:

2015-05-15

Now in database my dates : c_win like this : 现在在数据库中我的日期:c_win像这样:

2015-08-20 21:20:20

In the query I do : 在查询中,我做:

if ($date_min != '' && $date_max != ''){
        $aFilter = ' AND c_win > '.$date_min.' AND c_ig.date_gain < '.$date_max;
    }

But I think I need to reface the dates. 但是我认为我需要重提日期。 Help me please!! 请帮帮我!! Thx in advance 提前Thx

change the query like 像这样更改查询

 $aFilter = ' AND date(c_win) > '.$date_min.' AND date(c_ig.date_gain) < '.$date_max;

date function return only date like '2015-08-20' from '2015-08-20 21:20:20' date函数仅从“ 2015-08-20 21:20:20”返回类似“ 2015-08-20”的日期

i hope this is working for you. 我希望这对您有用。

Try using DATE() : 尝试使用DATE()

if ($date_min != '' && $date_max != ''){
    $aFilter = ' AND DATE(c_win) > "' . $date_min . '" AND DATE(c_ig.date_gain) < "' . $date_max . '"';
}

您需要在日期前后加引号

$aFilter = ' AND c_win > "'.$date_min.'" AND c_ig.date_gain < "'.$date_max.'"';

Don't wrap the column in DATE() as the optimizer can't use an index on the column.. plus I'd be binding in variables using PDO or mysqli rather than concatting them.. 不要将列包装在DATE()因为优化程序无法在列上使用索引。.另外,我将使用PDO或mysqli绑定变量,而不是将其封装。

When I have date comparisons in my code with date inputs, I almost always use: 当我在代码中使用日期输入进行日期比较时,几乎总是使用:

SELECT ...
  FROM table t
 WHERE t.time >= :min_date
   AND t.time <  :max_date + INTERVAL 1 DAY

Which exactly covers all the times between the dates without breaking the index. 它准确地覆盖了日期之间的所有时间,而没有破坏索引。 It also assumes that the dates provided are inclusive.. which is logical for a UI. 它还假定提供的日期包含在内。.这对于UI是合乎逻辑的。

In your case this would be: 在您的情况下,这将是:

$aFilter = ' AND c_win >= "'.$date_min.'" AND c_ig.date_gain < "'.$date_max.'" + INTERVAL 1 DAY';

BONUS INFO 奖金信息

If you are wondering why your query ran but didn't give the correct results.. 如果您想知道为什么查询运行了,但没有给出正确的结果。

AND c.win > 2008-05-13 AND c_ig.date_gain < 2015-05-05 

without quotes evaluates as integers to: 不带引号的整数计算为:

AND c.win > 1990 AND c_ig.date_gain < 2005

Which is then implicitly converted to: 然后将其隐式转换为:

AND c.win > "1990-01-01 00:00:00" AND c_ig.date_gain < "2005-01-01 00:00:00"

Another good reason not to concatenate query strings. 不连接查询字符串的另一个很好的理由。

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

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