简体   繁体   中英

using where clause and date range in sql query

I am having trouble pulling a query where i want to return results that contain a particular word in a field AND that are between a certain date range. The query i am using now is:

        $month_no = date('m');
        $month_day = date('d');         
        $query="SELECT * FROM `table` WHERE ((user_purchased LIKE '%john%') AND (request_date BETWEEN '2011-$month_no-$month_day' AND '2011-$month_no-$month_day')) ";
        $result = mysql_query($query);
        $num_rows = mysql_num_rows($result);  echo $num_rows;

My date format in the 'request_date field is like this: 2011-10-03 12:30:34

Any ideas on what i am doing wrong?

Thanks!

What happens if you try:

BETWEEN '2011-$month_no-$month_day 00:00:00' AND
'2011-$month_no-$month_day 23:59:59')) ";

鉴于您之间的日期范围相同,为什么不尝试

... WHERE (DATE(requested_date) = "2011-$month_no-$month_day")

Wild guess, as I only know how to do it with an Oracle DB - there you would use the *to_date* function as in

  ... WHERE date = TO_DATE('20110820','YYYYMMDD') ... 

or

  ... WHERE (date => TO_DATE('20110801','YYYYMMDD')) AND (date <= TO_DATE('20110831','YYYYMMDD')) 

Maybe it's worth checking if mysql needs such a function call also.

try

 $m = date('m');
  $d = date('d');
  $qry = " SELECT * FROM `table`
  WHERE ( requested_date BETWEEN DATE_FORMAT('2011-$m-$d', ''%Y-%m-%d'') 
                       AND DATE_FORMAT('2011-$m-$d', ''%Y-%m-%d'') )
  AND user_purchased LIKE '%john%' ";

If you want to check whether request_date (which I suppose is datetime) has date part '2011-$month_no-$month_day' , try this:

    $query="SELECT * FROM `table` 
            WHERE (user_purchased LIKE '%john%') 
              AND (request_date >= '2011-$month_no-$month_day')
              AND (request_date <  '2011-$month_no-$month_day' + INTERVAL 1 DAY)
            ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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