简体   繁体   中英

MySQL select all where date (stored in varchar type)

I have made a mistake when I originally designed my DB and I have an "appointments" table with ID, DATE, TIME but the type of DATE field is VARCHAR and I'm saving with this format: 29/08/2015

Now I would like to run a query that selects all appointments, 2 days from TODAY.

How can I do it?

Thanks

You should fix the column definition in the table and in the meanwhile to retrieve the data you need to use str_to_date function

select * from table_name
where str_to_date(DATE,'%d/%m/%Y') = date_add(now(),interval 2 day)

The varchar dates are not real date and will create more issues for different section, to fix the table column you can follow the steps as

step 1:

alter table table_name add column new_date date ;

step 2:

update table_name set new_date = str_to_date(DATE,'%d/%m/%Y');

step3 :

alter table_name drop column DATE ;
alter table_name change new_date DATE date

Use date(); .

$twoDaysFromNow = date('d/m/y', time() + 172800); // Adds exactly two days (172,800 seconds) to the current day, and returns it in given format.

$sql = "SELECT FROM `appointments` WHERE `date` = '{$twoDaysFromNow}'"; // Execute query with new date.

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