MySQL 8.0 Reference Manual(讀書筆記20節-- NULL+模式匹配+外鍵+自增屬性)

来源:https://www.cnblogs.com/xuliuzai/p/18129813
-Advertisement-
Play Games

生產環境有一套3個節點的MySQL InnoDB Cluster,MySQL的版本為Server version: 8.0.35 MySQL Community Server - GPL, 早上突然收到Zabbix的告警,其中一個節點出現空間告警:"/data: Disk space is low ...


1.NUll值

The NULL value can be surprising until you get used to it. Conceptually【kənˈsɛptʃuəli 概念;觀念上;概念上;在概念上;概念地;】, NULL means “a missing unknown value” and it is treated somewhat differently from other values.

To test for NULL, use the IS NULL and IS NOT NULL operators, as shown here:

mysql> SELECT 1 IS NULL, 1 IS NOT NULL;
+-----------+---------------+
| 1 IS NULL | 1 IS NOT NULL |
+-----------+---------------+
| 0         | 1             |
+-----------+---------------+

 You cannot use arithmetic comparison【kəmˈpærɪsn 比較;對比;相比;】 operators such as =, <, or <> to test for NULL. To demonstrate this for yourself, try the following query:

mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
+----------+-----------+----------+----------+
| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |
+----------+-----------+----------+----------+
| NULL     | NULL      | NULL     | NULL     |
+----------+-----------+----------+----------+

Because the result of any arithmetic comparison with NULL is also NULL, you cannot obtain any meaningful results from such comparisons.

In MySQL, 0 or NULL means false and anything else means true. The default truth value from a boolean operation is 1.

Two NULL values are regarded as equal in a GROUP BY.

When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC.

A common error when working with NULL is to assume that it is not possible to insert a zero or an empty string into a column defined as NOT NULL, but this is not the case. These are in fact values, whereas NULL means “not having a value.” You can test this easily enough by using IS [NOT] NULL as shown:

mysql> SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL;
+-----------+---------------+------------+----------------+
| 0 IS NULL | 0 IS NOT NULL | '' IS NULL | '' IS NOT NULL |
+-----------+---------------+------------+----------------+
| 0         | 1             | 0          | 1              |
+-----------+---------------+------------+----------------+

Thus it is entirely【ɪnˈtaɪərli 完全;完整地;全部地;】 possible to insert a zero or empty string into a NOT NULL column, as these are in fact NOT NULL.

 2.模式匹配

MySQL provides standard SQL pattern matching as well as a form of pattern matching based on extended regular expressions similar to those used by Unix utilities such as vi, grep, and sed.

2.1 通過 _ 和  %

SQL pattern matching enables you to use _ to match any single character and % to match an arbitrary number of characters (including zero characters). In MySQL, SQL patterns are case-insensitive by default. Some examples are shown here. Do not use = or <> when you use SQL patterns. Use the LIKE or NOT LIKE comparison operators instead.

2.2 通過extended regular expressions

The other type of pattern matching provided by MySQL uses extended regular expressions. When you test for a match for this type of pattern, use the REGEXP_LIKE() function (or the REGEXP or RLIKE operators, which are synonyms for REGEXP_LIKE()).

The following list describes some characteristics of extended regular expressions:

• . matches any single character

• A character class [...] matches any character within the brackets【ˈbrækɪts (固定在牆上的)托架,支架;括弧;(價格、年齡、收入等的)組級,等級;】. For example, [abc] matches a, b, or c. To name a range of characters, use a dash. [a-z] matches any letter, whereas [0-9] matches any digit.

• * matches zero or more instances of the thing preceding it. For example, x* matches any number of x characters, [0-9]* matches any number of digits, and .* matches any number of anything.

• A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested. (This differs from a LIKE pattern match, which succeeds only if the pattern matches the entire value.)

• To anchor a pattern so that it must match the beginning or end of the value being tested, use ^ at the beginning or $ at the end of the pattern.

 To demonstrate how extended regular expressions work, the LIKE queries shown previously are rewritten here to use REGEXP_LIKE().

To find names beginning with b, use ^ to match the beginning of the name: --開頭

mysql> SELECT * FROM pet WHERE REGEXP_LIKE(name, '^b');
+--------+--------+---------+------+------------+------------+
| name | owner    | species | sex  | birth      | death |
+--------+--------+---------+------+------------+------------+
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       |
| Bowser | Diane  | dog     | m    | 1979-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+

 To force a regular expression comparison to be case-sensitive, use a case-sensitive collation, or use the BINARY keyword to make one of the strings a binary string, or specify the c match-control character. Each of these queries matches only lowercase b at the beginning of a name:

SELECT * FROM pet WHERE REGEXP_LIKE(name, '^b' COLLATE utf8mb4_0900_as_cs);
SELECT * FROM pet WHERE REGEXP_LIKE(name, BINARY '^b');
SELECT * FROM pet WHERE REGEXP_LIKE(name, '^b', 'c');

To find names ending with fy, use $ to match the end of the name: ---結尾

mysql> SELECT * FROM pet WHERE REGEXP_LIKE(name, 'fy$');
+--------+--------+---------+------+------------+-------+
| name   | owner  | species | sex  | birth      | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL |
| Buffy | Harold  | dog     | f    | 1989-05-13 | NULL |
+--------+--------+---------+------+------------+-------+

To find names containing a w, use this query: ---不限位置的包含

mysql> SELECT * FROM pet WHERE REGEXP_LIKE(name, 'w');
+----------+-------+---------+------+------------+------------+
| name     | owner | species | sex  | birth      | death |
+----------+-------+---------+------+------------+------------+
| Claws    | Gwen  | cat     | m    | 1994-03-17 | NULL       |
| Bowser   | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL       |
+----------+-------+---------+------+------------+------------+

Because a regular expression pattern matches if it occurs anywhere in the value, it is not necessary in the previous query to put a wildcard【ˈwaɪldˌkɑrd (用於代替任何字元或字元串的)通配符;(給予沒有正常參賽資格的選手準其參加比賽的)“外卡”;“外卡”選手;未知數;未知因素;】 on either side of the pattern to get it to match the entire value as would be true with an SQL pattern.

To find names containing exactly five characters, use ^ and $ to match the beginning and end of the name, and five instances of . in between:

mysql> SELECT * FROM pet WHERE REGEXP_LIKE(name, '^.....$');
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

You could also write the previous query using the {n} (“repeat-n-times”) operator:

mysql> SELECT * FROM pet WHERE REGEXP_LIKE(name, '^.{5}$');
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL |
+-------+--------+---------+------+------------+-------+

 3.Using Foreign Keys

MySQL supports foreign keys, which permit cross-referencing related data across tables, and foreign key constraints, which help keep the related data consistent.

A foreign key relationship involves【ɪnˈvɑːlvz 需要;影響;(使)參加,加入;包含;牽涉;牽連;使成為必然部分(或結果);】 a parent table that holds the initial【ɪˈnɪʃl 開始的;最初的;第一的;】 column values, and a child table with column values that reference the parent column values. A foreign key constraint is defined on the child table.

This following example relates parent and child tables through a single-column foreign key and shows how a foreign key constraint enforces referential integrity.

Create the parent and child tables:

CREATE TABLE parent (
 id INT NOT NULL,
 PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
 id INT,
 parent_id INT,
 INDEX par_ind (parent_id),
 FOREIGN KEY (parent_id)
 REFERENCES parent(id)
) ENGINE=INNODB;

Insert a row into the child table with a parent_id value that is not present in the parent table:--報錯

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails 
(`test`.`child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) 
REFERENCES `parent` (`id`))

The operation fails because the specified parent_id value does not exist in the parent table.

Try to delete the previously inserted row from the parent table:--刪除父表中的數據,但是這筆數據,子表有參照,就會報錯

mysql> DELETE FROM parent WHERE id VALUES = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails 
(`test`.`child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) 
REFERENCES `parent` (`id`))

This operation fails because the record in the child table contains the referenced id (parent_id) value.

When an operation affects a key value in the parent table that has matching rows in the child table, the result depends on the referential action specified by ON UPDATE and ON DELETE subclauses【'sʌbklɔ:z 法律文件的)下設條款】 of the FOREIGN KEY clause. Omitting【əˈmɪtɪŋ 忽略;遺漏;刪除;漏掉;不做;未能做;】 ON DELETE and ON UPDATE clauses (as in the current child table definition) is the same as specifying the RESTRICT option, which rejects【rɪˈdʒekts 拒收;拒絕接受;拒絕接納;(因質量差)不用,不出售,不出版;不予考慮;不錄用;】 operations that affect a key value in the parent table that has matching rows in the parent table.

To demonstrate ON DELETE and ON UPDATE referential actions, drop the child table and recreate it to include ON UPDATE and ON DELETE subclauses with the CASCADE option. The CASCADE option automatically deletes or updates matching rows in the child table when deleting or updating rows in the parent table.

DROP TABLE child;
CREATE TABLE child (
 id INT,
 parent_id INT,
 INDEX par_ind (parent_id),
 FOREIGN KEY (parent_id)
 REFERENCES parent(id)
 ON UPDATE CASCADE
 ON DELETE CASCADE
) ENGINE=INNODB;

ON UPDATE CASCADE referential action updated the child table。--父變子已變

ON DELTE CASCADE referential action, delete records from the parent table,the ON DELETE CASCADE referential action removes all records from the child table。--刪除父表中的數據,子表中的數據,同時刪除。

 4.Using AUTO_INCREMENT

The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows。

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically.

If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.---你在insert語句中,雖然values值指明瞭null,自動生產AUTO INCREMENT的序列值

When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value.--如果自增列指明的插入值,以插入值為準。並且會重置基數值。

Updating an existing AUTO_INCREMENT column value also resets the AUTO_INCREMENT sequence.--更新語句也會重置基數值。

You can retrieve the most recent automatically generated AUTO_INCREMENT value with the LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function. These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts.

Use the smallest integer data type for the AUTO_INCREMENT column that is large enough to hold the maximum sequence value you require. When the column reaches the upper limit of the data type, the next attempt to generate a sequence number fails. Use the UNSIGNED attribute if possible to allow a greater range. For example, if you use TINYINT, the maximum permissible sequence number is 127. For TINYINT UNSIGNED, the maximum is 255.--小心取值範圍

說明

For a multiple-row insert, LAST_INSERT_ID() and mysql_insert_id() actually return the AUTO_INCREMENT key from the first of the inserted rows. This enables multiple-row inserts to be reproduced correctly on other servers in a replication setup.

----官網第三章《Tutorial 》

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 大家好,我是呼嚕嚕,在上一篇文章聊聊x86電腦啟動發生的事?我們瞭解了x86電腦啟動過程,MBR、0x7c00是什麼?其中當bios引導結束後,操作系統接過電腦的控制權後,發生了哪些事?本文將揭開迷霧的序章-Bootsect.S 回顧電腦啟動過程 我們先來回顧一下,上古時期電腦按下電源鍵的 ...
  • 大家好,我是痞子衡,是正經搞技術的痞子。今天痞子衡給大家介紹的是使能i.MXRT1050, 1060 Hab簽名或加密啟動時App鏈接在片內SRAM的限制。 最近有客戶反饋,在 RT1060 上測試 Non-XIP 程式啟動,如果程式體部分鏈接進 0x20280000 地址之後的片內 OCRAM 區 ...
  • 我的之前的博客《利用顯卡的SR-IOV虛擬GPU技術,實現一臺電腦當七台用》介紹了 Proxmox VE 7.x 上啟用核顯虛擬化的方法。 並給出了兩個腳本,快速啟用核顯的SR-IOV。該腳本在 Promox VE 7.x 和 8.x 都做了測試。 近期重新在 Proxmox VE 8.1 上部署, ...
  • 本次按照目前最新版本Sqlserver2022進行記錄 先決條件 任何受支持的 Linux 發行版上的 Docker 引擎 1.8 及更高版本。 有關詳細信息,請參閱 Install Docker(安裝 Docker)。 有關硬體要求和處理器支持的詳細信息,請參閱SQL Server 2022:硬體 ...
  • 點擊查看代碼 丐版sqlserver集群 之前試過docker的,k8s的,然後發現,還是最朴素的是最簡單的,希望有大佬能夠漢化,他媽的,那些英文看得人要發癲啊。 前置準備,參照丐版pxc集群: https://www.cnblogs.com/zwnfdswww/p/18112077 如果不關防火牆 ...
  • 背景介紹 近來一套業務系統,從庫一直處於延遲狀態,無法追上主庫,導致業務風險較大。從資源上看,從庫的CPU、IO、網路使用率較低,不存在伺服器壓力過高導致回放慢的情況;從庫開啟了並行回放;在從庫上執行show processlist看到沒有回放線程阻塞,回放一直在持續;解析relay-log日誌文件 ...
  • 作用 GROUP_CONCAT 是 MySQL 中用於將查詢結果集中的多行數據合併為單個字元串的聚合函數。它將每行數據的指定欄位值連接起來,並以指定的分隔符分隔,最終返回一個包含所有值的字元串。 以下是 GROUP_CONCAT 函數的一般語法: SELECT GROUP_CONCAT(column ...
  • 目錄一、Linux下MySQL忘記root密碼情景再現1、停止MySQL服務2、安全模式啟動MySQL服務,並暫時跳過許可權表驗證以及禁用網路連接3、更新mysql.user表中root用戶的密碼。4、刷新MySQL的許可權緩存二、Windows下MySQL忘記密碼(8.0以上版本)情景再現1、通過管理 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:本文代碼示例演示瞭如何在WPF中使用LiveCharts庫創建動態條形圖。通過創建數據模型、ViewModel和在XAML中使用`CartesianChart`控制項,你可以輕鬆實現圖表的數據綁定和動態更新。我將通過清晰的步驟指南包括詳細的中文註釋,幫助你快速理解並應用這一功能。 先上效果: 在 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • 概述:本示例演示了在WPF應用程式中實現多語言支持的詳細步驟。通過資源字典和數據綁定,以及使用語言管理器類,應用程式能夠在運行時動態切換語言。這種方法使得多語言支持更加靈活,便於維護,同時提供清晰的代碼結構。 在WPF中實現多語言的一種常見方法是使用資源字典和數據綁定。以下是一個詳細的步驟和示例源代 ...
  • 描述(做一個簡單的記錄): 事件(event)的本質是一個委托;(聲明一個事件: public event TestDelegate eventTest;) 委托(delegate)可以理解為一個符合某種簽名的方法類型;比如:TestDelegate委托的返回數據類型為string,參數為 int和 ...
  • 1、AOT適合場景 Aot適合工具類型的項目使用,優點禁止反編 ,第一次啟動快,業務型項目或者反射多的項目不適合用AOT AOT更新記錄: 實實在在經過實踐的AOT ORM 5.1.4.117 +支持AOT 5.1.4.123 +支持CodeFirst和非同步方法 5.1.4.129-preview1 ...
  • 總說周知,UWP 是運行在沙盒裡面的,所有許可權都有嚴格限制,和沙盒外交互也需要特殊的通道,所以從根本杜絕了 UWP 毒瘤的存在。但是實際上 UWP 只是一個應用模型,本身是沒有什麼許可權管理的,許可權管理全靠 App Container 沙盒控制,如果我們脫離了這個沙盒,UWP 就會放飛自我了。那麼有沒... ...
  • 目錄條款17:讓介面容易被正確使用,不易被誤用(Make interfaces easy to use correctly and hard to use incorrectly)限制類型和值規定能做和不能做的事提供行為一致的介面條款19:設計class猶如設計type(Treat class de ...
  • title: 從零開始:Django項目的創建與配置指南 date: 2024/5/2 18:29:33 updated: 2024/5/2 18:29:33 categories: 後端開發 tags: Django WebDev Python ORM Security Deployment Op ...
  • 1、BOM對象 BOM:Broswer object model,即瀏覽器提供我們開發者在javascript用於操作瀏覽器的對象。 1.1、window對象 視窗方法 // BOM Browser object model 瀏覽器對象模型 // js中最大的一個對象.整個瀏覽器視窗出現的所有東西都 ...