Rechercher dans le manuel MySQL

3.3.4.5 Date Calculations

MySQL provides several functions that you can use to perform calculations on dates, for example, to calculate ages or extract parts of dates.

To determine how many years old each of your pets is, use the TIMESTAMPDIFF() function. Its arguments are the unit in which you want the result expressed, and the two dates for which to take the difference. The following query shows, for each pet, the birth date, the current date, and the age in years. An alias (age) is used to make the final output column label more meaningful.

  1. mysql> SELECT name, birth, CURDATE(),
  2.        TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
  3.        FROM pet;
  4. +----------+------------+------------+------+
  5. | name     | birth      | CURDATE()  | age  |
  6. +----------+------------+------------+------+
  7. | Fluffy   | 1993-02-04 | 2003-08-19 |   10 |
  8. | Claws    | 1994-03-17 | 2003-08-19 |    9 |
  9. | Buffy    | 1989-05-13 | 2003-08-19 |   14 |
  10. | Fang     | 1990-08-27 | 2003-08-19 |   12 |
  11. | Bowser   | 1989-08-31 | 2003-08-19 |   13 |
  12. | Chirpy   | 1998-09-11 | 2003-08-19 |    4 |
  13. | Whistler | 1997-12-09 | 2003-08-19 |    5 |
  14. | Slim     | 1996-04-29 | 2003-08-19 |    7 |
  15. | Puffball | 1999-03-30 | 2003-08-19 |    4 |
  16. +----------+------------+------------+------+

The query works, but the result could be scanned more easily if the rows were presented in some order. This can be done by adding an ORDER BY name clause to sort the output by name:

  1. mysql> SELECT name, birth, CURDATE(),
  2.        TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
  3.        FROM pet ORDER BY name;
  4. +----------+------------+------------+------+
  5. | name     | birth      | CURDATE()  | age  |
  6. +----------+------------+------------+------+
  7. | Bowser   | 1989-08-31 | 2003-08-19 |   13 |
  8. | Buffy    | 1989-05-13 | 2003-08-19 |   14 |
  9. | Chirpy   | 1998-09-11 | 2003-08-19 |    4 |
  10. | Claws    | 1994-03-17 | 2003-08-19 |    9 |
  11. | Fang     | 1990-08-27 | 2003-08-19 |   12 |
  12. | Fluffy   | 1993-02-04 | 2003-08-19 |   10 |
  13. | Puffball | 1999-03-30 | 2003-08-19 |    4 |
  14. | Slim     | 1996-04-29 | 2003-08-19 |    7 |
  15. | Whistler | 1997-12-09 | 2003-08-19 |    5 |
  16. +----------+------------+------------+------+

To sort the output by age rather than name, just use a different ORDER BY clause:

  1. mysql> SELECT name, birth, CURDATE(),
  2.        TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
  3.        FROM pet ORDER BY age;
  4. +----------+------------+------------+------+
  5. | name     | birth      | CURDATE()  | age  |
  6. +----------+------------+------------+------+
  7. | Chirpy   | 1998-09-11 | 2003-08-19 |    4 |
  8. | Puffball | 1999-03-30 | 2003-08-19 |    4 |
  9. | Whistler | 1997-12-09 | 2003-08-19 |    5 |
  10. | Slim     | 1996-04-29 | 2003-08-19 |    7 |
  11. | Claws    | 1994-03-17 | 2003-08-19 |    9 |
  12. | Fluffy   | 1993-02-04 | 2003-08-19 |   10 |
  13. | Fang     | 1990-08-27 | 2003-08-19 |   12 |
  14. | Bowser   | 1989-08-31 | 2003-08-19 |   13 |
  15. | Buffy    | 1989-05-13 | 2003-08-19 |   14 |
  16. +----------+------------+------------+------+

A similar query can be used to determine age at death for animals that have died. You determine which animals these are by checking whether the death value is NULL. Then, for those with non-NULL values, compute the difference between the death and birth values:

  1. mysql> SELECT name, birth, death,
  2.        TIMESTAMPDIFF(YEAR,birth,death) AS age
  3.        FROM pet WHERE death IS NOT NULL ORDER BY age;
  4. +--------+------------+------------+------+
  5. | name   | birth      | death      | age  |
  6. +--------+------------+------------+------+
  7. | Bowser | 1989-08-31 | 1995-07-29 |    5 |
  8. +--------+------------+------------+------+

The query uses death IS NOT NULL rather than death <> NULL because NULL is a special value that cannot be compared using the usual comparison operators. This is discussed later. See Section 3.3.4.6, “Working with NULL Values”.

What if you want to know which animals have birthdays next month? For this type of calculation, year and day are irrelevant; you simply want to extract the month part of the birth column. MySQL provides several functions for extracting parts of dates, such as YEAR(), MONTH(), and DAYOFMONTH(). MONTH() is the appropriate function here. To see how it works, run a simple query that displays the value of both birth and MONTH(birth):

  1. mysql> SELECT name, birth, MONTH(birth) FROM pet;
  2. +----------+------------+--------------+
  3. | name     | birth      | MONTH(birth) |
  4. +----------+------------+--------------+
  5. | Fluffy   | 1993-02-04 |            2 |
  6. | Claws    | 1994-03-17 |            3 |
  7. | Buffy    | 1989-05-13 |            5 |
  8. | Fang     | 1990-08-27 |            8 |
  9. | Bowser   | 1989-08-31 |            8 |
  10. | Chirpy   | 1998-09-11 |            9 |
  11. | Whistler | 1997-12-09 |           12 |
  12. | Slim     | 1996-04-29 |            4 |
  13. | Puffball | 1999-03-30 |            3 |
  14. +----------+------------+--------------+

Finding animals with birthdays in the upcoming month is also simple. Suppose that the current month is April. Then the month value is 4 and you can look for animals born in May (month 5) like this:

  1. mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = 5;
  2. +-------+------------+
  3. | name  | birth      |
  4. +-------+------------+
  5. | Buffy | 1989-05-13 |
  6. +-------+------------+

There is a small complication if the current month is December. You cannot merely add one to the month number (12) and look for animals born in month 13, because there is no such month. Instead, you look for animals born in January (month 1).

You can write the query so that it works no matter what the current month is, so that you do not have to use the number for a particular month. DATE_ADD() enables you to add a time interval to a given date. If you add a month to the value of CURDATE(), then extract the month part with MONTH(), the result produces the month in which to look for birthdays:

  1. mysql> SELECT name, birth FROM pet
  2.        WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(),INTERVAL 1 MONTH));

A different way to accomplish the same task is to add 1 to get the next month after the current one after using the modulo function (MOD) to wrap the month value to 0 if it is currently 12:

  1. mysql> SELECT name, birth FROM pet
  2.        WHERE MONTH(birth) = MOD(MONTH(CURDATE()), 12) + 1;

MONTH() returns a number between 1 and 12. And MOD(something,12) returns a number between 0 and 11. So the addition has to be after the MOD(), otherwise we would go from November (11) to January (1).

If a calculation uses invalid dates, the calculation fails and produces warnings:

  1. mysql> SELECT '2018-10-31' + INTERVAL 1 DAY;
  2. +-------------------------------+
  3. | '2018-10-31' + INTERVAL 1 DAY |
  4. +-------------------------------+
  5. | 2018-11-01                    |
  6. +-------------------------------+
  7. mysql> SELECT '2018-10-32' + INTERVAL 1 DAY;
  8. +-------------------------------+
  9. | '2018-10-32' + INTERVAL 1 DAY |
  10. +-------------------------------+
  11. | NULL                          |
  12. +-------------------------------+
  13. mysql> SHOW WARNINGS;
  14. +---------+------+----------------------------------------+
  15. | Level   | Code | Message                                |
  16. +---------+------+----------------------------------------+
  17. | Warning | 1292 | Incorrect datetime value: '2018-10-32' |
  18. +---------+------+----------------------------------------+

Zoek in de MySQL-handleiding

Nederlandse vertaling

U hebt gevraagd om deze site in het Nederlands te bezoeken. Voor nu wordt alleen de interface vertaald, maar nog niet alle inhoud.

Als je me wilt helpen met vertalingen, is je bijdrage welkom. Het enige dat u hoeft te doen, is u op de site registreren en mij een bericht sturen waarin u wordt gevraagd om u toe te voegen aan de groep vertalers, zodat u de gewenste pagina's kunt vertalen. Een link onderaan elke vertaalde pagina geeft aan dat u de vertaler bent en heeft een link naar uw profiel.

Bij voorbaat dank.

Document heeft de 26/06/2006 gemaakt, de laatste keer de 26/10/2018 gewijzigd
Bron van het afgedrukte document:https://www.gaudry.be/nl/mysql-rf-date-calculations.html

De infobrol is een persoonlijke site waarvan de inhoud uitsluitend mijn verantwoordelijkheid is. De tekst is beschikbaar onder CreativeCommons-licentie (BY-NC-SA). Meer info op de gebruiksvoorwaarden en de auteur.

Referenties

  1. Bekijk - html-document Taal van het document:en Manuel MySQL : https://dev.mysql.com/

Deze verwijzingen en links verwijzen naar documenten die geraadpleegd zijn tijdens het schrijven van deze pagina, of die aanvullende informatie kunnen geven, maar de auteurs van deze bronnen kunnen niet verantwoordelijk worden gehouden voor de inhoud van deze pagina.
De auteur Deze site is als enige verantwoordelijk voor de manier waarop de verschillende concepten, en de vrijheden die met de referentiewerken worden genomen, hier worden gepresenteerd. Vergeet niet dat u meerdere broninformatie moet doorgeven om het risico op fouten te verkleinen.

Inhoudsopgave Haut