MySQL Select : where time is greater then and less than time

前端 未结 2 1201
梦谈多话
梦谈多话 2021-01-05 18:24

I have a function that accepts two time parameters: $start_time, $end_time each parameter is define as time in php as

$start_time          


        
相关标签:
2条回答
  • 2021-01-05 18:50

    The reason is because you are extracting the HOUR and comparing with the time, you need to cast the time part Try your query as::

    SELECT 
    
    * 
    FROM cdr_table 
    WHERE 
    OwnerUserID ='$_SESSION[user_id]' 
    AND GatewayID = $gateway_id 
    AND DATE(Dialed) = $date_sql 
    AND Dialed != 0 
    AND DATE_FORMAT(StartTime,'%r') BETWEEN ('$start_time') AND ('$end_time')
    
    0 讨论(0)
  • 2021-01-05 19:00

    You want TIME(), not HOUR().

    SELECT * FROM cdr_table 
    WHERE OwnerUserID = '$_SESSION[user_id]'
      AND GatewayID = $gateway_id
      AND DATE(Dialed) = $date_sql
      AND Dialed != 0
      AND TIME(StartTime) BETWEEN '$start_time' AND '$end_time'
    

    Also, I'd strongly suggest escaping all variables you're embedding in SQL code with mysql_real_escape_string() or equivalent, even if you're sure there's nothing harmful in them, just to make it a habit.

    Note that a query like this may be intrinsically inefficient, since it cannot make use of indexes on the StartTime column. If there are a lot of potentially matching rows in the table, it could be a good idea to denormalize your table by creating a separate column storing only the time part of the StartTime and setting up an index on it (possibly combined with other relevant columns).

    0 讨论(0)
提交回复
热议问题