简体   繁体   中英

How to get last record by date but a datatype varchar

I am trying to fetch data from a table with datatype varchar , but I need it to select the last 2 days using where clause by date.

Here I have tried from this link :

$query = $this
    ->db
    ->select('*, COUNT(*) as cnt')
    ->where('STR_TO_DATE(created_at,"%d-%m-%Y") >=', '(CURDATE() - INTERVAL 2 DAY)')
    ->group_by('client')
    ->order_by('cnt', 'DESC')
    ->get('histprob');

But the result is showing all data on my table instead of only two days passed. My column created_at is shown like: 06-02-2019 23:00

First make a date variable to compare as per your Database column "created_at"="06-02-2019 23:00"

$compare = date('d-m-Y G:i', strtotime('-2 days'));

Then make changes in where clause as below.

->where('created_at >=',$compare);

As per your comment, @Viren answe is not working with different months, so you can also try like that:

$currentDate = date('d-m-Y G:i');
$twoDaysOld = date('d-m-Y G:i', strtotime('-2 days'));

->where('created_at >=',$twoDaysOld); // greator equal to old date
->where('created_at <=',$currentDate); // less then and equal to current date

Here i am date range between two dates.

I have solved by converting created_at to date then compared it to $compare as suggested by Viren Panchal but changed the date format from 'dmY' to 'Ymd' as Mark Baker 's answers in compare dates not working also converted created_at by using STR_TO_DATE. Here is my completed code then:

$date7 = date('Y-m-d', strtotime('-7 days'));
$query = $this->db->select('*, COUNT(*) as cnt')->where('STR_TO_DATE(created_at,"%d-%m-%Y") >=', $date7)->group_by('client')->order_by('cnt', 'DESC')->get('histprob');

So, comparing date should use Y md?

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