在 SQL 中,视图是基于 SQL 语句的结果集的可视化的表
视图包含行和列,就像一个真实的表。视图中的字段就是来自一个或多个数据库中的真实的表中的字段。我们可以向视图添加 SQL 函数、WHERE 以及 JOIN 语句,我们也可以提交数据,就像这些来自于某个单一的表
注意:数据库的设计和结构不会受到视图中的函数、where 或 join 语句的影响
可以从某个查询内部、某个存储过程内部,或者从另一个视图内部来使用视图。通过向视图添加函数、join 等等,我们可以向用户精确地提交我们希望提交的数据
CREATE VIEW avg_list AS SELECT st.sname, sc.degree FROM student AS st LEFT OUTER JOIN score AS sc ON st.sno = sc.sno AND cno = "3-105" WHERE degree > (SELECT AVG(degree) FROM score);
Query OK, 0 rows affected (0.00 sec)
SELECT * FROM avg_list;
+--------+--------+
| sname | degree |
+--------+--------+
| 陆君 | 92 |
| 匡明 | 88 |
| 王丽 | 91 |
+--------+--------+
3 rows in set (0.00 sec)
查看视图状态
SHOW TABLE STATUS LIKE 'avg_list'\G
*************************** 1. row ***************************
Name: avg_list
Engine: NULL
Version: NULL
Row_format: NULL
Rows: NULL
Avg_row_length: NULL
Data_length: NULL
Max_data_length: NULL
Index_length: NULL
Data_free: NULL
Auto_increment: NULL
Create_time: NULL
Update_time: NULL
Check_time: NULL
Collation: NULL
Checksum: NULL
Create_options: NULL
Comment: VIEW
1 row in set (0.00 sec)
SHOW CREATE VIEW avg_list\G
*************************** 1. row ***************************
View: avg_list
Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `avg_list` AS select `st`.`sname` AS `sname`,`sc`.`degree` AS `degree` from (`student` `st` left join `score` `sc` on(`st`.`sno` = `sc`.`sno` and `sc`.`cno` = '3-105')) where `sc`.`degree` > (select avg(`score`.`degree`) from `score`)
character_set_client: utf8
collation_connection: utf8_general_ci
1 row in set (0.00 sec)
DROP VIEW IF EXISTS avg_list;
自定义函数将会保存在 mysql.proc 表中
mysql 默认不支持常见自定义函数,需要在 my.cnf 中的 mysqld 配置段中定义 log-bin-trust-function-creators=1 来声明支持自定义函数
参数可以有多个,也可以没有参数
必须有且只有一个返回值
CREATE FUNCTION testFunction() RETURNS VARCHAR(20) RETURN "Hello World!";
SELECT testFunction();
+----------------+
| testFunction() |
+----------------+
| Hello World! |
+----------------+
1 row in set (0.00 sec)
--将分隔符设置为//
DELIMITER //
CREATE FUNCTION testavg(subject VARCHAR(20)) RETURNS FLOAT
-> BEGIN
-> DECLARE a, b INT;
-> SELECT SUM(degree) INTO a FROM score WHERE cno = subject;
-> SELECT COUNT(cno) INTO B FROM score WHERE cno = subject;
-> RETURN a/b;
-> END//
Query OK, 0 rows affected (0.00 sec)
--将分隔符设置为;
DELIMITER ;
select testavg('3-105');
+------------------+
| testavg('3-105') |
+------------------+
| 81.5 |
+------------------+
1 row in set (0.00 sec)
查看函数状态
SHOW FUNCTION STATUS\G
查看函数定义
SHOW CREATE FUNCTION testavg\G
AVG 函数返回数值列的平均值。NULL 值不包括在计算中
SELECT AVG(degree) FROM score;
+-------------+
| AVG(degree) |
+-------------+
| 80.2500 |
+-------------+
1 row in set (0.00 sec)