简体   繁体   中英

Minus one date from another in MySQL request?

I have table with start_date and end_date . I need to find the duration ( end_date-start_date ). Can someone suggest how I can do so in the query? Will I get a new variable with this somehow like duration=end_date-start_date in the query?

EDIT If I use mminus it gives me:

2012-07-01 minus 2012-01-01 = 600

How can it be 600 days in 6 months as 2011-07-27 - 2011-07-06 = 21? So i assume it's days?
Is there function to get actually how many months it even if date is in middle of month. eg like "3rd june" and "27 july" is 2 month

use PERIOD_DIFF

Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values. so try

SELECT PERIOD_DIFF(
                   DATE_FORMAT('2011-07-27','%Y%m'),
                   DATE_FORMAT('2011-06-03','%Y%m')
                  ) AS durationInMonths

If you want to know DateTime different, you can use TimeDiff

select 
 (Hour(Duration) / 24)/365 as Year, 
 (Hour(Duration) / 24)%365 as Day, 
 (Hour(Duration) % 24) as Hours, 
 MINUTE(Duration) as Minutes, 
 SECOND(Duration) as Seconds
 from
(
SELECT ADDTIME(NOW(),'1000:27:50') as end_datetime, NOW() as start_datetime,
TIMEDIFF(ADDTIME(NOW(),'1000:27:50'), NOW()) AS Duration
) x;

If you want to know Date different, you can use DateDiff()

select DATEDIFF('2011-06-06','2011-05-01');

You can use * but to get duration, you need to add extra column after it

select *, DATEDIFF(updated_at, created_at) from users;

TO have the best practice, it is better naming u for user, duration for extra column. So you can see Duration title at the top. It is good if you export your sql procedure to excel.

select u.*, DATEDIFF(updated_at, created_at) as duration from users u;

Also from your php or rails code, you can call that given variable name. In rails,

users =User.find_by_sql("select u.*, DATEDIFF(updated_at, created_at) as duration from users u")

users.first.duration
SELECT end_date - start_date AS duration FROM table ...

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