數據庫 Mysql相關03

1. 組合查詢

多數SQL查詢都只包含從一個或多個表中返回數據的單條SELECT語句。MySQL也允許執行多個查詢(多條SELECT語句),並將結果作爲單個查詢結果集返回。這些組合查詢通常稱爲並(union)或複合查詢(compound query)。
有兩種基本情況,其中需要使用組合查詢:

  • 口在單個查詢中從不同的表返回類似結構的數據;
  • 口對單個表執行多個查詢,按單個查詢返回數據。

組合查詢和多個WHERE條件

多數情況下,組合相同表的兩個查詢完成的工作與具有多個WHERE子句條件的單條查詢完成的工作相同。換句話說,任何具有多個WHERE子句的SELECT語句都可以作爲一個組合查詢給出。這兩種技術在不同的查詢中性能也不同。因此,應該試一下這兩種技術,以確定對特定的查詢哪一種性能更好。

UNION與WHERE 

UNION幾乎總是完成與多個WHERE條件相同的工作,UNION ALL爲UNION的一種形式,它完成WHERE子句完成不了的工作。如果確實需要每個條件的匹配行全部出現(包括重複行),則必須使用UNION ALL而不是WHERE.

1.1 使用union

可用UNION操作符來組合數條SQL查詢。利用UNION,可給出多條select語句,將他們的結果組合成單個結果集。

mysql> select vend_id,prod_id,prod_price from products where prod_price <=5;
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|    1003 | FC      |       2.50 |
|    1002 | FU1     |       3.42 |
|    1003 | SLING   |       4.49 |
|    1003 | TNT1    |       2.50 |
+---------+---------+------------+
4 rows in set (0.00 sec)

mysql> select vend_id,prod_id,prod_price from products where vend_id in (1001,1002);
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|    1001 | ANV01   |       5.99 |
|    1001 | ANV02   |       9.99 |
|    1001 | ANV03   |      14.99 |
|    1002 | FU1     |       3.42 |
|    1002 | OL1     |       8.99 |
+---------+---------+------------+
5 rows in set (0.00 sec)

//第一條SELECT檢索價格不高於5的所有物品。第二條SELECT使用IN找出供應商1001和1002生產的所有物品。
//組合這兩條語句 使用union
//UNION指示MySQL執行兩條SELECT語句,並把輸出組合成單個查詢結果集
mysql> select vend_id,prod_id,prod_price from products where vend_id in (1001,1002)
    -> union select vend_id,prod_id,prod_price from products where prod_price <=5;
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|    1001 | ANV01   |       5.99 |
|    1001 | ANV02   |       9.99 |
|    1001 | ANV03   |      14.99 |
|    1002 | FU1     |       3.42 |
|    1002 | OL1     |       8.99 |
|    1003 | FC      |       2.50 |
|    1003 | SLING   |       4.49 |
|    1003 | TNT1    |       2.50 |
+---------+---------+------------+
8 rows in set (0.00 sec)

//作爲參考,這裏給出使用多條WHERE子句而不是使用UNION的相同查詢
mysql> select vend_id,prod_id,prod_price from products where prod_price <=5 or vend_id in(1001,1002);
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|    1001 | ANV01   |       5.99 |
|    1001 | ANV02   |       9.99 |
|    1001 | ANV03   |      14.99 |
|    1003 | FC      |       2.50 |
|    1002 | FU1     |       3.42 |
|    1002 | OL1     |       8.99 |
|    1003 | SLING   |       4.49 |
|    1003 | TNT1    |       2.50 |
+---------+---------+------------+
8 rows in set (0.00 sec)

//UNION從查詢結果集中自動去除了重複的行
//這是UNION的默認行爲,如果想返回所有匹配行,可使用UNION ALL而不是UNION.
mysql> select vend_id,prod_id,prod_price from products where vend_id in (1001,1002)
    -> union all select vend_id,prod_id,prod_price from products where prod_price <=5;
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|    1001 | ANV01   |       5.99 |
|    1001 | ANV02   |       9.99 |
|    1001 | ANV03   |      14.99 |
|    1002 | FU1     |       3.42 |
|    1002 | OL1     |       8.99 |
|    1003 | FC      |       2.50 |
|    1002 | FU1     |       3.42 |
|    1003 | SLING   |       4.49 |
|    1003 | TNT1    |       2.50 |
+---------+---------+------------+
9 rows in set (0.00 sec)

//對組合查詢結果進行排序
mysql> select vend_id,prod_id,prod_price from products where vend_id in (1001,1002)
    -> union all select vend_id,prod_id,prod_price from products where prod_price <=5 order by vend_id,prod_price;
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|    1001 | ANV01   |       5.99 |
|    1001 | ANV02   |       9.99 |
|    1001 | ANV03   |      14.99 |
|    1002 | FU1     |       3.42 |
|    1002 | FU1     |       3.42 |
|    1002 | OL1     |       8.99 |
|    1003 | FC      |       2.50 |
|    1003 | TNT1    |       2.50 |
|    1003 | SLING   |       4.49 |
+---------+---------+------------+
9 rows in set (0.00 sec)

 

2. 全文本搜索

並非所有引擎都支持全文本搜索

MySQL支持幾種基本的數據庫引擎,並非所有的引擎都支持本書所描述的全文本搜索。兩個最常使用的引擎爲My ISAM和InnoDB,前者支持全文本搜索,而後者不支持。樣例表(productnotes表)使用MyISAM。如果你的應用中需要全文本搜索功能,應該記住這一點。

在使用全文本搜索時,MySQL不需要分別查看每個行,不需要分別分析和處理每個詞。MySQL創建指定列中各詞的一個索引,搜索可以針對這些詞進行。這樣,MySQL可以快速有效地決定哪些詞匹配(哪些行包含它們),哪些詞不匹配,它們匹配的頻率,等等。

2.1 使用全文本搜索

一般在創建表時啓用全文本搜索。CREATE TABLE語句 接受FULLTEXT子句,它給出被索引列的一個逗號分隔的列表。

mysql> show create table productnotes;
+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table        | Create Table                                                                                                                                                                                                                                                                               |
+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| productnotes | CREATE TABLE `productnotes` (
  `note_id` int(11) NOT NULL AUTO_INCREMENT,
  `prod_id` char(10) NOT NULL,
  `note_date` datetime NOT NULL,
  `note_text` text,
  PRIMARY KEY (`note_id`),
  FULLTEXT KEY `note_text` (`note_text`)
) ENGINE=MyISAM AUTO_INCREMENT=115 DEFAULT CHARSET=utf8 |
+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

列中有一個名爲note_text的列,爲了進行全文本搜索,MySQL根據子句FULLTEXT(note_text)的指示對它進行索引。這裏的FULLTEXT索引單個列,如果需要也可以指定多個列。
在定義之後,MySQL自動維護該索引。在增加、更新或刪除行時,索引隨之自動更新。
可以在創建表時指定FULLTEXT,或者在稍後指定(在這種情況下所有已有數據必須立即索引)。

不要在導入數據時使用FULLTEXT

更新索引要花時間,雖然不是很多,但畢竟要花時間。如果正在導入數據到一個新表,此時不應該啓用FULLTEXT索引.應該首先導入所有數據,然後再修改表,定義FULLTEXT.這樣有助於更快地導入數據(而且使索引數據的總時間小於在導入每行時分別進行索引所需的總時間)。

2.2 進行全文本搜索

在索引之後,使用兩個函數Match()和Against()執行全文本搜索,

其中Match()指定被搜索的列,Against()指定要使用的搜索表達式。

mysql> select * from productnotes;
+---------+---------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------+
| note_id | prod_id | note_date           | note_text                                                                                                                                                  |
+---------+---------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------+
|     101 | TNT2    | 2005-08-17 00:00:00 | Customer complaint:
Sticks not individually wrapped, too easy to mistakenly detonate all at once.
Recommend individual wrapping.                         |
|     102 | OL1     | 2005-08-18 00:00:00 | Can shipped full, refills not available.
Need to order new can if refill needed.                                                                          |
|     103 | SAFE    | 2005-08-18 00:00:00 | Safe is combination locked, combination not provided with safe.
This is rarely a problem as safes are typically blown up or dropped by customers.         |
|     104 | FC      | 2005-08-19 00:00:00 | Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait.                                      |
|     105 | TNT2    | 2005-08-20 00:00:00 | Included fuses are short and have been known to detonate too quickly for some customers.
Longer fuses are available (item FU1) and should be recommended. |
|     106 | TNT2    | 2005-08-22 00:00:00 | Matches not included, recommend purchase of matches or detonator (item DTNTR).                                                                             |
|     107 | SAFE    | 2005-08-23 00:00:00 | Please note that no returns will be accepted if safe opened using explosives.                                                                              |
|     108 | ANV01   | 2005-08-25 00:00:00 | Multiple customer returns, anvils failing to drop fast enough or falling backwards on purchaser. Recommend that customer considers using heavier anvils.   |
|     109 | ANV03   | 2005-09-01 00:00:00 | Item is extremely heavy. Designed for dropping, not recommended for use with slings, ropes, pulleys, or tightropes.                                        |
|     110 | FC      | 2005-09-01 00:00:00 | Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                                                               |
|     111 | SLING   | 2005-09-02 00:00:00 | Shipped unassembled, requires common tools (including oversized hammer).                                                                                   |
|     112 | SAFE    | 2005-09-02 00:00:00 | Customer complaint:
Circular hole in safe floor can apparently be easily cut with handsaw.                                                                |
|     113 | ANV01   | 2005-09-05 00:00:00 | Customer complaint:
Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead.   |
|     114 | SAFE    | 2005-09-07 00:00:00 | Call from individual trapped in safe plummeting to the ground, suggests an escape hatch be added.
Comment forwarded to vendor.                            |
+---------+---------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------+
14 rows in set (0.00 sec)

//Match(note_text)指示MySQL針對指定的列進行搜索
//Against('rabbit')指定詞rabbit作爲搜索文本。
mysql> select note_text from productnotes where match(note_text) against('rabbit');
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                          |
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
+-----------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.01 sec)

//上述搜索也可用like完成
mysql> select note_text from productnotes where note_text like '%rabbit%';
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
| Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                          |
+-----------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

上述兩條SELECT語句都不包含ORDER BY子句。後者(使用LIKE)以不特別有用的順序返回數據。前者(使用全文本搜索)返回以文本匹配的良好程度排序的數據。兩個行都包含詞rabbit,但包含詞rabbit作爲第3個詞的行的等級比作爲第20個詞的行高。這很重要。全文本搜索的一個重要部分就是對結果排序。具有較高等級的行先返回(因爲這些行很可能是你真正想要的行)。

mysql> select note_text,match(note_text) against('rabbit') as rank from productnotes\G;
*************************** 1. row ***************************
note_text: Customer complaint:
Sticks not individually wrapped, too easy to mistakenly detonate all at once.
Recommend individual wrapping.
     rank: 0
*************************** 2. row ***************************
note_text: Can shipped full, refills not available.
Need to order new can if refill needed.
     rank: 0
*************************** 3. row ***************************
note_text: Safe is combination locked, combination not provided with safe.
This is rarely a problem as safes are typically blown up or dropped by customers.
     rank: 0
*************************** 4. row ***************************
note_text: Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait.
     rank: 1.5905543565750122
*************************** 5. row ***************************
note_text: Included fuses are short and have been known to detonate too quickly for some customers.
Longer fuses are available (item FU1) and should be recommended.
     rank: 0
*************************** 6. row ***************************
note_text: Matches not included, recommend purchase of matches or detonator (item DTNTR).
     rank: 0
*************************** 7. row ***************************
note_text: Please note that no returns will be accepted if safe opened using explosives.
     rank: 0
*************************** 8. row ***************************
note_text: Multiple customer returns, anvils failing to drop fast enough or falling backwards on purchaser. Recommend that customer considers using heavier anvils.
     rank: 0
*************************** 9. row ***************************
note_text: Item is extremely heavy. Designed for dropping, not recommended for use with slings, ropes, pulleys, or tightropes.
     rank: 0
*************************** 10. row ***************************
note_text: Customer complaint: rabbit has been able to detect trap, food apparently less effective now.
     rank: 1.6408053636550903
*************************** 11. row ***************************
note_text: Shipped unassembled, requires common tools (including oversized hammer).
     rank: 0
*************************** 12. row ***************************
note_text: Customer complaint:
Circular hole in safe floor can apparently be easily cut with handsaw.
     rank: 0
*************************** 13. row ***************************
note_text: Customer complaint:
Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead.
     rank: 0
*************************** 14. row ***************************
note_text: Call from individual trapped in safe plummeting to the ground, suggests an escape hatch be added.
Comment forwarded to vendor.
     rank: 0
14 rows in set (0.00 sec)

ERROR:
No query specified

在SELECT而不是WHERE子句中使用Match()和Against()。這使所有行都被返回(因爲沒有WHERE子句),Match()和Against()用來建立一個計算列(別名爲rank),此列包含全文本搜索計算出的等級值。等級由MySQL根據行中詞的數目、唯一詞的數目、整個索引中詞的總數以及包含該詞的行的數目計算出來。正如所見,不包含詞rabbit的行等級爲0(因此不被前一例子中的WHERE子句選擇)。確實包含詞rabbit的兩個行每行都有一個等級值,文本中詞靠前的行的等級值比詞靠後的行的等級值高。

2.3 使用查詢擴展

mysql> select note_text from productnotes where match(note_text) against('anvils');
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Multiple customer returns, anvils failing to drop fast enough or falling backwards on purchaser. Recommend that customer considers using heavier anvils. |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

//使用查詢擴展
mysql> select note_text from productnotes where match(note_text) against('anvils' with query expansion);
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Multiple customer returns, anvils failing to drop fast enough or falling backwards on purchaser. Recommend that customer considers using heavier anvils. |
| Customer complaint:
Sticks not individually wrapped, too easy to mistakenly detonate all at once.
Recommend individual wrapping.                       |
| Customer complaint:
Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead. |
| Please note that no returns will be accepted if safe opened using explosives.                                                                            |
| Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                                                             |
| Customer complaint:
Circular hole in safe floor can apparently be easily cut with handsaw.                                                              |
| Matches not included, recommend purchase of matches or detonator (item DTNTR).                                                                           |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
7 rows in set (0.00 sec)

2.4 布爾文本搜索

即使沒有FULLTEXT索引也可以使用

布爾方式不同於迄今爲止使用的全文本搜索語法的地方在於,即使沒有定義FULLTEXT索引,也可以使用它。但這是一種非常緩慢的操作(其性能將隨着數據量的增加而降低)。

//此全文本搜索檢索包含詞heavy的所有行(有兩行)。
//其中使用分析了關鍵字IN BOOLEAN MODE,但實際上沒有指定布爾操作符
//因此,其結果與沒有指定布爾方式的結果相同。
mysql> select note_text from productnotes where match(note_text) against('heavy' in boolean mode);
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Item is extremely heavy. Designed for dropping, not recommended for use with slings, ropes, pulleys, or tightropes.                                      |
| Customer complaint:
Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead. |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

//匹配包含heavy但不包含任意以rope開始的詞的行
mysql> select note_text from productnotes where match(note_text) against('heavy -rope*' in boolean mode);
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Customer complaint:
Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead. |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

//匹配包含詞rabbit和bait的行
mysql> select note_text from productnotes where match(note_text) against('+rabbit +bait' in boolean mode);
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

//沒有指定操作符,這個搜索匹配包含rabbit和bait 的至少一個詞的行。
mysql> select note_text from productnotes where match(note_text) against('rabbit bait' in boolean mode);
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
| Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                          |
+-----------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

//這個搜索匹配短語rabbit bait而不是匹配兩個詞rabbit和bait.
mysql> select note_text from productnotes where match(note_text) against('"rabbit bait"' in boolean mode);
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

//匹配rabbit和carrot,增加前者的等級,降低後者的等級。
mysql> select note_text from productnotes where match(note_text) against('>rabbit <bait' in boolean mode);
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
| Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                          |
+-----------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> select note_text from productnotes where match(note_text) against('rabbit bait' in boolean mode);
+-----------------------------------------------------------------------------------------------------------------------+
| note_text                                                                                                             |
+-----------------------------------------------------------------------------------------------------------------------+
| Quantity varies, sold by the sack load.
All guaranteed to be bright and orange, and suitable for use as rabbit bait. |
| Customer complaint: rabbit has been able to detect trap, food apparently less effective now.                          |
+-----------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

3. 插入數據

mysql> describe customers;
+--------------+-----------+------+-----+---------+----------------+
| Field        | Type      | Null | Key | Default | Extra          |
+--------------+-----------+------+-----+---------+----------------+
| cust_id      | int(11)   | NO   | PRI | NULL    | auto_increment |
| cust_name    | char(50)  | NO   |     | NULL    |                |
| cust_address | char(50)  | YES  |     | NULL    |                |
| cust_city    | char(50)  | YES  |     | NULL    |                |
| cust_state   | char(5)   | YES  |     | NULL    |                |
| cust_zip     | char(10)  | YES  |     | NULL    |                |
| cust_country | char(50)  | YES  |     | NULL    |                |
| cust_contact | char(50)  | YES  |     | NULL    |                |
| cust_email   | char(255) | YES  |     | NULL    |                |
+--------------+-----------+------+-----+---------+----------------+
9 rows in set (0.01 sec)

//插入完整的行
mysql> insert into customers values(null,'aa','sxhj','hjs','a','1234','china',null,null);
Query OK, 1 row affected (0.01 sec)

//插入行的一部分
mysql> insert into customers(cust_name,cust_city,cust_state) values('bb','sxyc','b');
Query OK, 1 row affected (0.00 sec)

mysql> insert into customers(cust_name,cust_email,cust_city,cust_country) values('cc','[email protected]','sxhj','china');
Query OK, 1 row affected (0.01 sec)

//插入多行
mysql> insert into customers(cust_name,cust_email,cust_city,cust_country) values('dd','[email protected]','sxhj','china'),('ee','[email protected]','sxhj','ch');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

//插入某些查詢的結果
mysql> insert into customers(cust_name,cust_email,cust_city,cust_country) select cust_name,cust_email,cust_city,cust_country from customers where cust_id=10010;
Query OK, 1 row affected (0.01 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from customers;
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
| cust_id | cust_name      | cust_address        | cust_city | cust_state | cust_zip | cust_country | cust_contact | cust_email          |
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
|   10001 | Coyote Inc.    | 200 Maple Lane      | Detroit   | MI         | 44444    | USA          | Y Lee        | [email protected]     |
|   10002 | Mouse House    | 333 Fromage Lane    | Columbus  | OH         | 43333    | USA          | Jerry Mouse  | NULL                |
|   10003 | Wascals        | 1 Sunny Place       | Muncie    | IN         | 42222    | USA          | Jim Jones    | [email protected] |
|   10004 | Yosemite Place | 829 Riverside Drive | Phoenix   | AZ         | 88888    | USA          | Y Sam        | [email protected]    |
|   10005 | E Fudd         | 4545 53rd Street    | Chicago   | IL         | 54545    | USA          | E Fudd       | NULL                |
|   10006 | aa             | sxhj                | hjs       | a          | 1234     | china        | NULL         | NULL                |
|   10007 | bb             | NULL                | sxyc      | b          | NULL     | NULL         | NULL         | NULL                |
|   10008 | cc             | NULL                | sxhj      | NULL       | NULL     | china        | NULL         | [email protected]         |
|   10009 | dd             | NULL                | sxhj      | NULL       | NULL     | china        | NULL         | [email protected]         |
|   10010 | ee             | NULL                | sxhj      | NULL       | NULL     | ch           | NULL         | [email protected]         |
|   10011 | ee             | NULL                | sxhj      | NULL       | NULL     | ch           | NULL         | [email protected]         |
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
11 rows in set (0.00 sec)

提高整體性能

數據庫經常被多個客戶訪問,對處理什麼請求以及用什麼次序處理進行管理是MysQL的任務。INSERT操作可能很耗時(特別是有很多索引需要更新時),而且它可能降低等待處理的SELECT語句的性能。
如果數據檢索是最重要的(通常是這樣),則你可以通過在INSERT和INTO之間添加關鍵字LOW-PRIORITY,指示MySQL降低INSERT語句的優先級,如下所示:

INSERT LOW_PRIORITY INTO

這也適用於UPDATE和DELETE語句。

提高INSERT的性能

此技術可以提高數據庫處理的性能,因爲MySQL用單條INSERT語句處理多個插入比使用多條INSERT語句快。

4. 更新和刪除數據

mysql> update customers set cust_email='[email protected]' where cust_id=10011;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

//注意 ","
mysql> update customers set cust_email='[email protected]',cust_name='eeeee' where cust_id=10011;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

//刪除某個列的值,可設置它爲NULL
mysql> update customers set cust_country=null where cust_id=10011;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> delete from customers where cust_id=10012;
Query OK, 1 row affected (0.01 sec)

mysql> select * from customers;
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
| cust_id | cust_name      | cust_address        | cust_city | cust_state | cust_zip | cust_country | cust_contact | cust_email          |
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
|   10001 | Coyote Inc.    | 200 Maple Lane      | Detroit   | MI         | 44444    | USA          | Y Lee        | [email protected]     |
|   10002 | Mouse House    | 333 Fromage Lane    | Columbus  | OH         | 43333    | USA          | Jerry Mouse  | NULL                |
|   10003 | Wascals        | 1 Sunny Place       | Muncie    | IN         | 42222    | USA          | Jim Jones    | [email protected] |
|   10004 | Yosemite Place | 829 Riverside Drive | Phoenix   | AZ         | 88888    | USA          | Y Sam        | [email protected]    |
|   10005 | E Fudd         | 4545 53rd Street    | Chicago   | IL         | 54545    | USA          | E Fudd       | NULL                |
|   10006 | aa             | sxhj                | hjs       | a          | 1234     | china        | NULL         | NULL                |
|   10007 | bb             | NULL                | sxyc      | b          | NULL     | NULL         | NULL         | NULL                |
|   10008 | cc             | NULL                | sxhj      | NULL       | NULL     | china        | NULL         | [email protected]         |
|   10009 | dd             | NULL                | sxhj      | NULL       | NULL     | china        | NULL         | [email protected]         |
|   10010 | ee             | NULL                | sxhj      | NULL       | NULL     | ch           | NULL         | [email protected]         |
|   10011 | eeeee          | NULL                | sxhj      | NULL       | NULL     | NULL         | NULL         | [email protected]      |
|   10013 | ee             | NULL                | sxhj      | NULL       | NULL     | ch           | NULL         | [email protected]         |
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
12 rows in set (0.00 sec)

在UPDATE語句中使用子查詢

UPDATE語句中可以使用子查詢,使得能用SELECT語句檢索出的數據更新列數據。

IGNORE關鍵字

如果用UPDATE語句更新多行,並且在更新這些行中的一行或多行時出一個現錯誤,則整個UPDATE操作被取消(錯誤發生前更新的所有行被恢復到它們原來的值),爲即使是發生錯誤,也繼續進行更新,可使用IGNORE關鍵字,如下所示:

UPDATE IGNORE customers..

刪除表的內容而不是表

DELETE語句從表中刪除行,甚至是刪除表中所有行。但是,DELETE不刪除表本身。

更快的刪除

如果想從表中刪除所有行,不要使用DELETE。可使用TRUNCATE TABLE語句,它完成相同的工作,但速度更快

(TRUNCATE實際是刪除原來的表並重新創建一個表,而不是逐行刪除表中的數據)。

如果省略了WHERE子句,則UPDATE或DELETE將被應用到表中所有的行。換句話說,如果執行UPDATE而不帶WHERE子句,則表中每個行都將用新值更新。類似地,如果執行DELETE語句而不帶WHERE子句,表的所有數據都將被刪除。

使用強制實施引用完整性的數據庫,這樣MysQL將不 許刪除具有與其他表相關聯的數據的行。

維護引用完整性

重要的是,要理解聯結不是物理實體。換句話說,它在實際的數據庫表中不存在。聯結由MySQL根據需要建立,它存在於查詢的執行當中。
在使用關係表時,僅在關係列中插入合法的數據非常重要。如果在products表中插入擁有非法供應商ID(即沒有在vendors表中出現)的供應商生產的產品,則這些產品是不可訪問的,因爲它們沒有關聯到某個供應商。
爲防止這種情況發生,可指示MySQL只允許在products表的供應商ID列中出現合法值(即出現在vendors表中的供應商)
這就是維護引用完整性,它是通過在表的定義中指定主鍵和外鍵來實現的。

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章