mysql> help show; Name: 'SHOW' Description: SHOW has many forms that provide information about databases, tables, columns, or status information about the server. This section describes those following:
SHOW {BINARY | MASTER} LOGS SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count] SHOW CHARACTER SET [like_or_where] SHOW COLLATION [like_or_where] SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [like_or_where] SHOW CREATE DATABASE db_name SHOW CREATE EVENT event_name SHOW CREATE FUNCTION func_name SHOW CREATE PROCEDURE proc_name SHOW CREATE TABLE tbl_name SHOW CREATE TRIGGER trigger_name SHOW CREATE VIEW view_name SHOW DATABASES [like_or_where] SHOW ENGINE engine_name {STATUS | MUTEX} SHOW [STORAGE] ENGINES SHOW ERRORS [LIMIT [offset,] row_count] SHOW EVENTS SHOW FUNCTION CODE func_name SHOW FUNCTION STATUS [like_or_where] SHOW GRANTS FOR user SHOW INDEX FROM tbl_name [FROM db_name] SHOW MASTER STATUS SHOW OPEN TABLES [FROM db_name] [like_or_where] SHOW PLUGINS SHOW PROCEDURE CODE proc_name SHOW PROCEDURE STATUS [like_or_where] SHOW PRIVILEGES SHOW [FULL] PROCESSLIST SHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n] SHOW PROFILES SHOW RELAYLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count] SHOW SLAVE HOSTS SHOW SLAVE STATUS [FOR CHANNEL channel] SHOW [GLOBAL | SESSION] STATUS [like_or_where] SHOW TABLE STATUS [FROM db_name] [like_or_where] SHOW [FULL] TABLES [FROM db_name] [like_or_where] SHOW TRIGGERS [FROM db_name] [like_or_where] SHOW [GLOBAL | SESSION] VARIABLES [like_or_where] SHOW WARNINGS [LIMIT [offset,] row_count]
like_or_where: { LIKE 'pattern' | WHERE expr }
If the syntax for a given SHOW statement includes a LIKE 'pattern' part, 'pattern' is a string that can contain the SQL % and _ wildcard characters. The pattern is useful for restricting statement output to matching values.
Several SHOW statements also accept a WHERE clause that provides more flexibility in specifying which rows to display. See https://dev.mysql.com/doc/refman/8.0/en/extended-show.html.
mysql> show grants; +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Grants for root@localhost | +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`localhost` WITH GRANT OPTION | | GRANT APPLICATION_PASSWORD_ADMIN,AUDIT_ADMIN,BACKUP_ADMIN,BINLOG_ADMIN,BINLOG_ENCRYPTION_ADMIN,CLONE_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GROUP_REPLICATION_ADMIN,INNODB_REDO_LOG_ARCHIVE,INNODB_REDO_LOG_ENABLE,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_APPLIER,REPLICATION_SLAVE_ADMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SERVICE_CONNECTION_ADMIN,SESSION_VARIABLES_ADMIN,SET_USER_ID,SHOW_ROUTINE,SYSTEM_USER,SYSTEM_VARIABLES_ADMIN,TABLE_ENCRYPTION_ADMIN,XA_RECOVER_ADMIN ON *.* TO `root`@`localhost` WITH GRANT OPTION | | GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION | +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 3 rows in set (0.00 sec)
mysql> select prod_name -> from products -> where prod_name regexp '1000|2000' -> order by prod_name; +--------------+ | prod_name | +--------------+ | JetPack 1000 | | JetPack 2000 | +--------------+ 2 rows in set (0.00 sec)
3. 匹配几个字符之一
[] 是另一种形式的 OR 语句,[123] 相当于 [1|2|3] :
1 2 3 4 5 6 7 8 9 10 11
mysql> select prod_name -> from products -> where prod_name regexp '[123] Ton' -> order by prod_name; +-------------+ | prod_name | +-------------+ | 1 ton anvil | | 2 ton anvil | +-------------+ 2 rows in set (0.00 sec)
| 默认应用于整个串,除非放置在集合中,1|2|3 Ton 表示匹配 1 或 2 或 3 Ton :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
mysql> select prod_name -> from products -> where prod_name regexp '1|2|3 Ton' -> order by prod_name; +---------------+ | prod_name | +---------------+ | 1 ton anvil | | 2 ton anvil | | JetPack 1000 | | JetPack 2000 | | TNT (1 stick) | +---------------+ 5 rows in set (0.00 sec)
mysql> select prod_name -> from products -> where prod_name not regexp '[123]' -> order by prod_name; +----------------+ | prod_name | +----------------+ | .5 ton anvil | | Bird seed | | Carrots | | Detonator | | Fuses | | Oil can | | Safe | | Sling | | TNT (5 sticks) | +----------------+ 9 rows in set (0.00 sec)
4. 匹配范围
使用 - 定义一个范围,[1-5] 表示匹配 1 ~ 5 共 5 个数字:
1 2 3 4 5 6 7 8 9 10 11 12
mysql> select prod_name -> from products -> where prod_name regexp '[1-5] Ton' -> order by prod_name; +--------------+ | prod_name | +--------------+ | .5 ton anvil | | 1 ton anvil | | 2 ton anvil | +--------------+ 3 rows in set (0.00 sec)
5. 匹配特殊字符
正则表达式中的特殊字符必须使用 \\ 为前导进行匹配
这就是所谓的转义(escaping)
\\ 也用来引用元字符(具有特殊含义的字符)
使用 \\\ 匹配反斜杠
空白元字符
元字符
说明
\\f
换页
\\n
换行
\\r
回车
\\t
制表
\\v
纵向制表
例如,匹配 . 的正则表达式为 \\. :
1 2 3 4 5 6 7 8 9 10
mysql> select vend_name -> from vendors -> where vend_name regexp '\\.' -> order by vend_name; +--------------+ | vend_name | +--------------+ | Furball Inc. | +--------------+ 1 row in set (0.01 sec)
6. 匹配字符类
预定义的字符集,称为字符类(character class)
Character Class Name
Meaning
alnum
Alphanumeric characters
alpha
Alphabetic characters
blank
Whitespace characters
cntrl
Control characters
digit
Digit characters
graph
Graphic characters
lower
Lowercase alphabetic characters
print
Graphic or space characters
punct
Punctuation characters
space
Space, tab, newline, and carriage return
upper
Uppercase alphabetic characters
xdigit
Hexadecimal digit characters
使用 [:alnum:] 匹配字母和数字:
1 2 3 4 5 6 7
mysql> SELECT REGEXP_LIKE('justalnums', '[[:alnum:]]+'); +-------------------------------------------+ | REGEXP_LIKE('justalnums', '[[:alnum:]]+') | +-------------------------------------------+ | 1 | +-------------------------------------------+ 1 row in set (0.01 sec)
mysql> select prod_name -> from products -> where prod_name regexp '^[0-9\\.]' -> order by prod_name; +--------------+ | prod_name | +--------------+ | .5 ton anvil | | 1 ton anvil | | 2 ton anvil | +--------------+ 3 rows in set (0.00 sec)
mysql> select vend_name, -> Upper(vend_name) as vend_name_upcase -> from vendors -> order by vend_name; +----------------+------------------+ | vend_name | vend_name_upcase | +----------------+------------------+ | ACME | ACME | | Anvils R Us | ANVILS R US | | Furball Inc. | FURBALL INC. | | Jet Set | JET SET | | Jouets Et Ours | JOUETS ET OURS | | LT Supplies | LT SUPPLIES | +----------------+------------------+ 6 rows in set (0.00 sec)
mysql> select cust_name, cust_contact -> from customers -> where Soundex(cust_contact) = Soundex('Y Lie'); +-------------+--------------+ | cust_name | cust_contact | +-------------+--------------+ | Coyote Inc. | Y Lee | +-------------+--------------+ 1 row in set (0.00 sec)
可以把一条 SELECT 语句返回的结果用在另一条 SELECT 语句的 WHERE 子句中。例如,根据订单号检索购买了 TNT2 的客户:
1 2 3 4 5 6 7 8 9 10 11 12 13
mysql> select cust_id -> from orders -> where order_num in( -> select order_num -> from orderitems -> where prod_id = 'TNT2'); +---------+ | cust_id | +---------+ | 10001 | | 10004 | +---------+ 2 rows in set (0.00 sec)
嵌套多个子查询,根据订单号检索购买了 TNT2 的客户,再根据客户 ID 检索客户的姓名:
在 WHERE 子句中使用子查询,应该保证 SELECT 语句和 WHERE 子句具有相同数目的列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
mysql> select cust_name, cust_contact -> from customers -> where cust_id in( -> select cust_id -> from orders -> where order_num in( -> select order_num -> from orderitems -> where prod_id = 'TNT2')); +----------------+--------------+ | cust_name | cust_contact | +----------------+--------------+ | Coyote Inc. | Y Lee | | Yosemite Place | Y Sam | +----------------+--------------+ 2 rows in set (0.00 sec)
mysql> select cust_name, -> cust_state, -> (select count(*) -> from orders -> where orders.cust_id=customers.cust_id) as orders -> from customers -> order by cust_name; +----------------+------------+--------+ | cust_name | cust_state | orders | +----------------+------------+--------+ | Coyote Inc. | MI | 2 | | E Fudd | IL | 1 | | Mouse House | OH | 0 | | Wascals | IN | 1 | | Yosemite Place | AZ | 1 | +----------------+------------+--------+ 5 rows in set (0.00 sec)
mysql> select vend_name, prod_name, prod_price -> from vendors inner join products -> on vendors.vend_id = products.vend_id -> order by vend_name, prod_name; +-------------+----------------+------------+ | vend_name | prod_name | prod_price | +-------------+----------------+------------+ | ACME | Bird seed | 10.00 | | ACME | Carrots | 2.50 | | ACME | Detonator | 13.00 | | ACME | Safe | 50.00 | | ACME | Sling | 4.49 | | ACME | TNT (1 stick) | 2.50 | | ACME | TNT (5 sticks) | 10.00 | | Anvils R Us | .5 ton anvil | 5.99 | | Anvils R Us | 1 ton anvil | 9.99 | | Anvils R Us | 2 ton anvil | 14.99 | | Jet Set | JetPack 1000 | 35.00 | | Jet Set | JetPack 2000 | 55.00 | | LT Supplies | Fuses | 3.42 | | LT Supplies | Oil can | 8.99 | +-------------+----------------+------------+ 14 rows in set (0.00 sec)
连接的表的数量没有限制,但是连接的表越多,性能越差。例如,检索订单号为 20005 的订单中的物品,用 WHERE 子句匹配表中的列:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
mysql> select prod_name, vend_name, prod_price, quantity -> from orderitems, products, vendors -> where products.vend_id = vendors.vend_id -> and orderitems.prod_id = products.prod_id -> and order_num = 20005; +----------------+-------------+------------+----------+ | prod_name | vend_name | prod_price | quantity | +----------------+-------------+------------+----------+ | .5 ton anvil | Anvils R Us | 5.99 | 10 | | 1 ton anvil | Anvils R Us | 9.99 | 3 | | TNT (5 sticks) | ACME | 10.00 | 5 | | Bird seed | ACME | 10.00 | 1 | +----------------+-------------+------------+----------+ 4 rows in set (0.00 sec)
将上一节中三层嵌套的子查询进行化简:
1 2 3 4 5 6 7 8 9 10 11 12
mysql> select cust_name, cust_contact -> from customers, orders, orderitems -> where customers.cust_id = orders.cust_id -> and orderitems.order_num = orders.order_num -> and prod_id = 'TNT2'; +----------------+--------------+ | cust_name | cust_contact | +----------------+--------------+ | Coyote Inc. | Y Lee | | Yosemite Place | Y Sam | +----------------+--------------+ 2 rows in set (0.00 sec)
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.00 sec)
上面的语句也可以使用 LIKE 完成:
1 2 3 4 5 6 7 8 9 10 11
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)
全文本搜索对结果进行排序,先返回具有较高等级的行。等级由 MySQL 根据行中词的数目、唯一词的数目、整个索引中词的总数以及包含该次的行数计算得出。因此不包含 rabbit 的行的等级为 0 ,包含 rabbit 的行具有非零等级:
mysql> select note_text, MATCH (note_text) AGAINST('rabbit') -> from productnotes; +-----------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------+ | note_text | MATCH (note_text) AGAINST('rabbit') | +-----------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------+ | Customer complaint: Sticks not individually wrapped, too easy to mistakenly detonate all at once. Recommend individual wrapping. | 0 | | Can shipped full, refills not available. Need to order new can if refill needed. | 0 | | Safe is combination locked, combination not provided with safe. This is rarely a problem as safes are typically blown up or dropped by customers. | 0 | | Quantity varies, sold by the sack load. All guaranteed to be bright and orange, and suitable for use as rabbit bait. | 1.5905543565750122 | | 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. | 0 | | Matches not included, recommend purchase of matches or detonator (item DTNTR). | 0 | | Please note that no returns will be accepted if safe opened using explosives. | 0 | | Multiple customer returns, anvils failing to drop fast enough or falling backwards on purchaser. Recommend that customer considers using heavier anvils. | 0 | | Item is extremely heavy. Designed for dropping, not recommended for use with slings, ropes, pulleys, or tightropes. | 0 | | Customer complaint: rabbit has been able to detect trap, food apparently less effective now. | 1.6408053636550903 | | Shipped unassembled, requires common tools (including oversized hammer). | 0 | | Customer complaint: Circular hole in safe floor can apparently be easily cut with handsaw. | 0 | | Customer complaint: Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead. | 0 | | Call from individual trapped in safe plummeting to the ground, suggests an escape hatch be added. Comment forwarded to vendor. | 0 | +-----------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------+ 14 rows in set (0.00 sec)
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)
使用 WITH QUERY EXPANSION 放宽搜索范围:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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)
没有使用 FULLTEXT() 定义索引也可以使用布尔全文本搜索,但是相比建立索引的搜索性能较差。使用 IN BOOLEAN MODE 指定布尔全文本搜索,- 表示排除文本,+ 表示必须包含文本,布尔全文本搜索排列但不排序。
下列语句表示检索包含 heavy 但不包含以 rope 开始的词的行:
1 2 3 4 5 6 7 8 9 10
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 :
1 2 3 4 5 6 7 8 9 10
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 :
1 2 3 4 5 6 7 8 9 10 11
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 :
1 2 3 4 5 6 7 8 9 10
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)
增加前者的等级,降低后者的等级:
1 2 3 4 5 6 7 8 9 10 11
mysql> select note_text -> from productnotes -> where MATCH(note_text) AGAINST('>rabbit <carrot' 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)
匹配词 safe 和 combination,降低后者的等级:
1 2 3 4 5 6 7 8 9 10
mysql> select note_text -> from productnotes -> where MATCH(note_text) AGAINST('+safe +(<combination>)' IN BOOLEAN MODE); +---------------------------------------------------------------------------------------------------------------------------------------------------+ | 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. | +---------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
mysql> select * from customers where cust_country = 'USA'; +---------+----------------+---------------------+------------+------------+----------+--------------+--------------+---------------------+ | 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 | ylee@coyote.com | | 10002 | Mouse House | 333 Fromage Lane | Columbus | OH | 43333 | USA | Jerry Mouse | NULL | | 10003 | Wascals | 1 Sunny Place | Muncie | IN | 42222 | USA | Jim Jones | rabbit@wascally.com | | 10004 | Yosemite Place | 829 Riverside Drive | Phoenix | AZ | 88888 | USA | Y Sam | sam@yosemite.com | | 10005 | E Fudd | 4545 53rd Street | Chicago | IL | 54545 | USA | E Fudd | NULL | | 10008 | Pep E. LaPew | 100 Main Street | Los Angles | CA | 90046 | USA | NULL | NULL | | 10009 | M. Martian | 42 Galaxy Way | New York | NY | 11213 | USA | NULL | NULL | +---------+----------------+---------------------+------------+------------+----------+--------------+--------------+---------------------+ 7 rows in set (0.00 sec)
mysql> select * from custnew; +---------+----------------+---------------------+------------+------------+----------+--------------+--------------+---------------------+ | 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 | ylee@coyote.com | | 10002 | Mouse House | 333 Fromage Lane | Columbus | OH | 43333 | USA | Jerry Mouse | NULL | | 10003 | Wascals | 1 Sunny Place | Muncie | IN | 42222 | USA | Jim Jones | rabbit@wascally.com | | 10004 | Yosemite Place | 829 Riverside Drive | Phoenix | AZ | 88888 | USA | Y Sam | sam@yosemite.com | | 10005 | E Fudd | 4545 53rd Street | Chicago | IL | 54545 | USA | E Fudd | NULL | | 10008 | Pep E. LaPew | 100 Main Street | Los Angles | CA | 90046 | USA | NULL | NULL | | 10009 | M. Martian | 42 Galaxy Way | New York | NY | 11213 | USA | NULL | NULL | +---------+----------------+---------------------+------------+------------+----------+--------------+--------------+---------------------+ 7 rows in set (0.00 sec)
mysql> CREATE VIEW productcustomers AS -> SELECT cust_name, cust_contact, prod_id -> FROM customers, orders, orderitems -> WHERE customers.cust_id = orders.cust_id -> AND orderitems.order_num = orders.order_num; Query OK, 0 rows affected (0.01 sec)
用视图检索购买了 TNT2 的客户:
1 2 3 4 5 6 7 8 9 10
mysql> select cust_name, cust_contact -> from productcustomers -> where prod_id = 'TNT2'; +----------------+--------------+ | cust_name | cust_contact | +----------------+--------------+ | Coyote Inc. | Y Lee | | Yosemite Place | Y Sam | +----------------+--------------+ 2 rows in set (0.00 sec)
格式化数据
检索供应商和位置的格式化数据:
1 2 3 4 5 6
mysql> CREATE VIEW vendorlocation AS -> SELECT CONCAT(RTRIM(vend_name), '(', RTrim(vend_country), ')') -> AS vend_title -> FROM vendors -> ORDER BY vend_name; Query OK, 0 rows affected (0.00 sec)
从视图中检索格式化的数据:
1 2 3 4 5 6 7 8 9 10 11 12
mysql> select * from vendorlocation; +------------------------+ | vend_title | +------------------------+ | ACME(USA) | | Anvils R Us(USA) | | Furball Inc.(USA) | | Jet Set(England) | | Jouets Et Ours(France) | | LT Supplies(USA) | +------------------------+ 6 rows in set (0.00 sec)
过滤数据
创建过滤没有邮件地址的客户的视图:
1 2 3 4 5
mysql> CREATE VIEW customeremaillist AS -> SELECT cust_id, cust_name, cust_email -> FROM customers -> WHERE cust_email IS NOT NULL; Query OK, 0 rows affected (0.01 sec)
从视图中检索拥有邮件地址的客户:
1 2 3 4 5 6 7 8 9
mysql> select * from customeremaillist; +---------+----------------+---------------------+ | cust_id | cust_name | cust_email | +---------+----------------+---------------------+ | 10001 | Coyote Inc. | ylee@coyote.com | | 10003 | Wascals | rabbit@wascally.com | | 10004 | Yosemite Place | sam@yosemite.com | +---------+----------------+---------------------+ 3 rows in set (0.00 sec)
计算字段
创建视图计算每种物品的总和:
1 2 3 4 5 6 7 8
mysql> CREATE VIEW orderitemsexpanded AS -> SELECT order_num, -> prod_id, -> quantity, -> item_price, -> quantity*item_price AS expanded_price -> FROM orderitems; Query OK, 0 rows affected (0.01 sec)
mysql> CREATE PROCEDURE productpricing( -> OUT pl DECIMAL(8,2), -> OUT ph DECIMAL(8,2), -> OUT pa DECIMAL(8,2) -> ) -> BEGIN -> SELECT MIN(prod_price) -> INTO pl -> FROM products; -> SELECT MAX(prod_price) -> INTO ph -> FROM products; -> SELECT AVG(prod_price) -> INTO pa -> FROM products; -> END// Query OK, 0 rows affected (0.00 sec)
接受订单号并返回该订单的合计:
1 2 3 4 5 6 7 8 9 10 11
mysql> CREATE PROCEDURE ordertotal( -> IN onumber INT, -> OUT ototal DECIMAL(8,2) -> ) -> BEGIN -> SELECT SUM(item_price*quantity) -> FROM orderitems -> WHERE order_num = onumber -> INTO ototal; -> END// Query OK, 0 rows affected (0.01 sec)
-- Declare local variables DECLARE done BOOLEANDEFAULT0; DECLARE o INT; DECLARE t DECIMAL(8,2); -- Declare the cursor DECLARE ordernumbers CURSOR FOR SELECT order_num FROM orders;
mysql> CREATE TABLE ordertotals( -> id int NOT NULL AUTO_INCREMENT, -> order_num int NOT NULL, -> total int NOT NULL, -> PRIMARY KEY (id) -> ); Query OK, 0 rows affected (0.02 sec)
CREATETRIGGER deleteorder BEFORE DELETEON orders FOREACHROW BEGIN INSERTINTO archive_orders(order_num, order_date, cust_id) VALUES(OLD.order_num, OLD.order_date, OLD.cust_id); END
UPDATE
在 UPDATE 触发器内,可以引用一个名为 OLD 的虚拟表,访问旧值,引用一个名为 NEW 的虚拟表,访问新值
在 BEFORE UPDATE 出发其中,NEW 中的值也可以被更新(允许更改被更新的值)
OLD 中的值全部是只读的
保证州名缩写总是大写:
1 2
CREATETRIGGER updatevendor BEFORE UPDATEON vendors FOREACHROWSET NEW.vend_state =Upper(NEW.vend_state);
mysql> SELECT * FROM customers -> ORDER BY cust_name, cust_address COLLATE utf8mb4_general_ci; +---------+----------------+---------------------+------------+------------+----------+--------------+--------------+---------------------+ | 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 | ylee@coyote.com | | 10009 | M. Martian | 42 Galaxy Way | New York | NY | 11213 | USA | NULL | NULL | | 10002 | Mouse House | 333 Fromage Lane | Columbus | OH | 43333 | USA | Jerry Mouse | NULL | | 10007 | Pep E. LaPew | 100 Main Street | Los Angles | CA | 90046 | USA | NULL | NULL | | 10008 | Pep E. LaPew | 100 Main Street | Los Angles | CA | 90046 | USA | NULL | NULL | | 10005 | The Fudds | 4545 53rd Street | Chicago | IL | 54545 | USA | E Fudd | NULL | | 10003 | Wascals | 1 Sunny Place | Muncie | IN | 42222 | USA | Jim Jones | rabbit@wascally.com | | 10004 | Yosemite Place | 829 Riverside Drive | Phoenix | AZ | 88888 | USA | Y Sam | sam@yosemite.com | +---------+----------------+---------------------+------------+------------+----------+--------------+--------------+---------------------+ 8 rows in set (0.00 sec)
mysql> select user,authentication_string from mysql.user where user LIKE 'cat'; +------+------------------------------------------------------------------------+ | user | authentication_string | +------+------------------------------------------------------------------------+ | cat | $A$005$g1*ZeB!vr)F:2`E;dUfKlOQ.F3Q8469sRKIvvfAccTP8SlR627FYnTStLj.n2 | +------+------------------------------------------------------------------------+ 1 row in set (0.00 sec)
mysql> SET PASSWORD FOR cat = 'n3w p@$$w0rd'; Query OK, 0 rows affected (0.00 sec)
mysql> select user,authentication_string from mysql.user where user LIKE 'cat'; +------+------------------------------------------------------------------------+ | user | authentication_string | +------+------------------------------------------------------------------------+ | cat | $A$005$.'r; Go^j0wm+wf6rpiUsskXasKT3FpbPDJcrJmF28N21dj1u2JfVZok8 | +------+------------------------------------------------------------------------+ 1 row in set (0.00 sec)
使用 DROP USER 删除用户账号(以及相关的权限):
1 2 3 4 5 6 7 8 9 10 11 12 13 14
mysql> DROP USER cat; Query OK, 0 rows affected (0.01 sec)
mysql> SELECT user FROM mysql.user; +------------------+ | user | +------------------+ | root | | mysql.infoschema | | mysql.session | | mysql.sys | | root | +------------------+ 5 rows in set (0.00 sec)
访问权限
使用 SHOW GRANTS FOR 查看授予用户的权限:
USAGE 表示没有对任意数据库和数据表都没有权限
MySQL 的权限用用户名和主机名结合定义,如果不指定主机名,则使用默认的主机名 %
1 2 3 4 5 6 7
mysql> SHOW GRANTS FOR cat; +---------------------------------+ | Grants for cat@% | +---------------------------------+ | GRANT USAGE ON *.* TO `cat`@`%` | +---------------------------------+ 1 row in set (0.00 sec)
使用 GRANT 语句设置权限,授予 cat 用户对 crashcourse 数据库中所有数据的只读权限,再次查看权限:
1 2 3 4 5 6 7 8 9 10 11
mysql> GRANT SELECT ON crashcourse.* TO cat; Query OK, 0 rows affected (0.00 sec)
mysql> SHOW GRANTS FOR cat; +----------------------------------------------+ | Grants for cat@% | +----------------------------------------------+ | GRANT USAGE ON *.* TO `cat`@`%` | | GRANT SELECT ON `crashcourse`.* TO `cat`@`%` | +----------------------------------------------+ 2 rows in set (0.00 sec)
REVOKE 用于撤销特定的权限,撤销刚才授予 cat 用户的权限:
1 2 3 4 5 6 7 8 9 10
mysql> REVOKE SELECT ON crashcourse.* FROM cat; Query OK, 0 rows affected (0.01 sec)
mysql> SHOW GRANTS FOR cat; +---------------------------------+ | Grants for cat@% | +---------------------------------+ | GRANT USAGE ON *.* TO `cat`@`%` | +---------------------------------+ 1 row in set (0.00 sec)