如何从mysql查询中的两个日期获取岁月和剩余天数

时间:2017-11-23 09:56:08

标签: mysql

我有两个约会:1860-07-21和1920-04-23。 通过这部分查询,我得到了日期之间的总天数:

DATEDIFF(str_to_date(concat(Right(FirstTime,2),"-", Mid(FirstTime,6,2),"-",Left(FirstTime,4)),'%d-%m-%Y'), str_to_date(concat(Right(Born,2),"-", Mid(Born,6,2),"-",Left(Born,4)),'%d-%m-%Y')) as Days

结果是21825天。我应该如何修改上面的查询部分以获得59年和277天?

1 个答案:

答案 0 :(得分:0)

使用TIMESTAMPDIFF()

SELECT

  @yearsDiff:=(TIMESTAMPDIFF(
    YEAR,
    str_to_date(concat(Right(FirstTime,2),'-', Mid(FirstTime,6,2),'-',Left(FirstTime,4)),'%d-%m-%Y'),
    str_to_date(concat(Right(Born,2),'-', Mid(Born,6,2),'-',Left(Born,4)),'%d-%m-%Y')
  )) as YEARS,

  TIMESTAMPDIFF(
    DAY,
    DATE_ADD(str_to_date(concat(Right(FirstTime,2),'-', Mid(FirstTime,6,2),'-',Left(FirstTime,4)),'%d-%m-%Y'), INTERVAL @yearsDiff YEAR),
    str_to_date(concat(Right(Born,2),'-', Mid(Born,6,2),'-',Left(Born,4)),'%d-%m-%Y')
  ) as DAYS

FROM (SELECT '1860-07-21' AS FirstTime, '1920-04-23' AS Born) AS t