简体   繁体   中英

how to add one year from the most recent date in the same table from SQL?

so I create a query that managed to add one year from the most recent date in the same table like this:

DATE_ADD(SELECT max(order_date) FROM order WHERE id_order = '$id', INTERVAL 1 YEAR)

but it gave an error near SELECT

A subquery needs to be in its own set of parentheses. But in this case, it is better to put the calculation in the subquery:

(SELECT DATE_ADD(max(order_date), INTERVAL 1 YEAR)
 FROM order
 WHERE id_order = '$id'
) as colname

Addition to a date works in the order of days. So you just need the most recent (max) date and add 365 days to it:

SELECT
  MAX(order_date) + 365
FROM order

Fair point made by Widor that this is basic arithmetic so does not take into account leap years. Certain RDBMS INTERVAL arithmetic have bugs with leap years too. Now the question has been clarified as mysql, see Gordon Linoff's answer using DATE_ADD and the mysql INTERVAL

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