MySQL 8.0 Reference Manual(读书笔记19节-- 日期与计算)

这篇具有很好参考价值的文章主要介绍了MySQL 8.0 Reference Manual(读书笔记19节-- 日期与计算)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.age 与 出生日期

为什么设计的时候,存放的是出生日期而不是年龄呢?这个问题简单,细想很有意思,也包含着智慧,来自生产生活的思考。下面的解释很到位。

How about age? That might be of interest, but it is not a good thing to store in a database. Age changes as time passes, which means you'd have to update your records often. Instead, it is better to store a fixed value such as date of birth. Then, whenever you need age, you can calculate it as the difference between the current date and the birth date. MySQL provides functions for doing date arithmetic, so this is not difficult.

---日期是出生是固化不变的,而年龄是动态变化的。

Storing birth date rather than age has other advantages, too:

• You can use the database for tasks such as generating reminders【riˈmaɪndərz (告知该做某事的)通知单,提示信;引起回忆的事物;提醒人的事物;】 for upcoming birthdays. ( If you think this type of query is somewhat silly【ˈsɪli 愚蠢的;傻的;(尤指像小孩一样)可笑的,荒唐的,冒傻气的;没头脑的;闹着玩的;不实用的;不明事理的;】, note that it is the same question you might ask in the context【ˈkɑːntekst 上下文;(事情发生的)背景,环境,来龙去脉;语境;】 of【in the context of 在…的背景下;在…背景下;在……情况下;】 a business database to identify clients to whom you need to send out birthday greetings in the current week or month, for that computer-assisted personal touch. )

• You can calculate age in relation to dates other than the current date. For example, if you store death date in the database, you can easily calculate how old a pet was when it died.

The use of the DATE data type for the birth and death columns is a fairly【ˈferli 相当地;(用以强调)简直,竟然;公正地;公平合理地;一定地;】 obvious【ˈɑːbviəs 明显的;显然的;当然的;公认的;平淡无奇的;易理解的;无创意的;因显而易见而不必要的;】 choice.

2. 样本案例

假设设计的一张用来保存宠物【pet】基本信息的表:

mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
 species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);

数据

mysql> SELECT * FROM pet;
+----------+--------+---------+------+------------+------------+
| name     | owner  | species | sex  | birth      | death |
+----------+--------+---------+------+------------+------------+
| Fluffy   | Harold | cat     | f    | 1993-02-04 | NULL |
| Claws    | Gwen   | cat     | m    | 1994-03-17 | NULL |
| Buffy    | Harold | dog     | f    | 1989-05-13 | NULL |
| Fang     | Benny  | dog     | m    | 1990-08-27 | NULL |
| Bowser   | Diane  | dog     | m    | 1979-08-31 | 1995-07-29 |
| Chirpy   | Gwen   | bird    | f    | 1998-09-11 | NULL |
| Whistler | Gwen   | bird    | NULL | 1997-12-09 | NULL |
| Slim     | Benny  | snake   | m    | 1996-04-29 | NULL |
| Puffball | Diane  | hamster | f    | 1999-03-30 | NULL |
+----------+--------+---------+------+------------+------------+

3.关于日期的计算需求

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

3.1 通过TIMESTAMPDIFF()计算时差--求年龄

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.

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

计算存活多少时间

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:

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

NUll值要特别小心

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.

3.2 计算(刷选出)下个月过生日的记录

--YEAR(), MONTH(), and DAYOFMONTH()

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): --先算一个简单的,计算出生日的月份

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

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;
+-------+------------+
| name  | birth |
+-------+------------+
| Buffy | 1989-05-13 |
+-------+------------+

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). --显然是不合理的,如果12月,怎么吗? 简单+1,不是13月了吗?这是个笑话。

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:

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

另外一个解法,就是借助mod()

mod(),取模运算函数,返回两个数相除的余数。

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【[ræp 包;裹(礼物等);(使文字)换行;用…包裹(或包扎、覆盖等);用…缠绕(或围紧);】 the month value to 0 if it is currently 12:

mysql> SELECT name, birth FROM pet
 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).

 

---官网第三章《Tutorial 》文章来源地址https://www.toymoban.com/news/detail-847921.html

到了这里,关于MySQL 8.0 Reference Manual(读书笔记19节-- 日期与计算)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • MySQL 8.0 Reference Manual(读书笔记34节-- 字符编码(1))

    MySQL includes character【ˈkærəktər 字母,符号;】 set support that enables you to store data using a variety【vəˈraɪəti (同一事物的)不同种类,多种式样; 变化; (植物、语言等的)变种,变体; 多样化; 综艺节目; 品种; 多变性; 异体; 】 of character sets and perform comparisons【kəmˈpɛrəsənz 比较; 对比

    2024年04月13日
    浏览(34)
  • MySQL 8.0 Reference Manual(读书笔记36节-- 字符编码(3))

    Regardless of how you configure the MySQL character set for application use, you must also consider the environment within which those applications execute. For example, if you intend to send statements using UTF-8 text taken from a file that you create in an editor, you should edit the file with the locale of your environment set to UTF-8 so that the file e

    2024年04月13日
    浏览(64)
  • MySQL 8.0 Reference Manual(读书笔记67节--Phantom Rows)

    The so-called phantom problem occurs within a transaction when the same query produces different sets of rows at different times. For example, if a SELECT is executed twice, but returns a row the second time that was not returned the first time, the row is a “phantom” row. Suppose that there is an index on the id column of the child table and that you wa

    2024年03月23日
    浏览(34)
  • MySQL 8.0 Reference Manual(读书笔记65节--InnoDBLocks Set)

    A locking read, an UPDATE, or a DELETE generally set record locks on every index record that is scanned in the processing of an SQL statement. It does not matter whether there are WHERE conditions in the statement that would exclude the row. InnoDB does not remember the exact【ɪɡˈzækt 准确的; 精确的; 严格的; 精密的; 严谨的; 严密的; 一丝

    2024年04月22日
    浏览(35)
  • MySQL 8.0 Reference Manual(读书笔记64节--InnoDBTransaction Model)

    The InnoDB transaction model aims to combine the best properties【ˈprɑpərtiz 财产; 特性; 房地产; 不动产; 财物; 庄园; 所有物; 房屋及院落; 】 of a multi-versioning database with traditional two-phase locking. InnoDB performs locking at the row level and runs queries as nonlocking consistent reads by default, in the style of Oracle. T

    2024年04月22日
    浏览(38)
  • MySQL 8.0 Reference Manual(读书笔记63节--InnoDB Locking)

    To implement a large-scale, busy, or highly reliable database application, to port substantial【səbˈstænʃl】 code from a different database system, or to tune MySQL performance, it is important to understand InnoDB locking and the InnoDB transaction model. InnoDB implements【ˈɪmplɪments 实施; 执行; 贯彻; 使生效; 】 standard row-level lock

    2024年04月22日
    浏览(32)
  • MySQL 8.0 Reference Manual(读书笔记41节-- Data Types(3))

    Data type specifications can have explicit【ɪkˈsplɪsɪt 明确的; 详述的; 直言的, 坦率的; 一目了然的; 】 or implicit【ɪmˈplɪsɪt 含蓄的; 完全的; 内含的; 无疑问的; 不直接言明的; 成为一部分的; 】 default values. A DEFAULT value clause in a data type specification explicitly indicates a default value for a colum

    2024年04月17日
    浏览(25)
  • MySQL 8.0 Reference Manual(读书笔记39节-- Data Types(1))

    Data type descriptions use these conventions: • For integer types, M indicates the maximum display width. For floating-point and fixed-point types, M is the total number of digits that can be stored (the precision). For string types, M is the maximum length. The maximum permissible value of M depends on the data type. • D applies to floating-point and fi

    2024年04月16日
    浏览(34)
  • MySQL 8.0 Reference Manual(读书笔记40节-- Data Types(2))

    The string data types are CHAR, VARCHAR, BINARY, VARBINARY, BLOB, TEXT, ENUM, and SET. In some cases, MySQL may change a string column to a type different from that given in a CREATE TABLE or ALTER TABLE statement.  For definitions of character string columns (CHAR, VARCHAR, and the TEXT types), MySQL interprets【ɪnˈtɜːrprəts 诠释; 说明; 把…理解

    2024年04月17日
    浏览(53)
  • MySQL 8.0 Reference Manual(读书笔记69节--InnoDB Startup Configuration)

    有些InnoDB的配置,是在实例初始化时,就决定了,所以,建议写在configuration file 文件中。 Because MySQL uses data file, log file, and page size settings to initialize InnoDB, it is recommended that you define these settings in an option file that MySQL reads at startup, prior to initializing InnoDB. Normally, InnoDB is initialize

    2024年03月24日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包