本文实例讲述了mysql视图之确保视图的一致性(with check option)操作。分享给大家供大家参考,具体如下:
我们有的时候,会创建一个视图来显示表的部分数据。我们知道,简单视图是的,因此可以更新通过视图不可见的数据,但是此更新会使的视图不一致。为了确保视图的一致性,在创建或修改视图时使用WITH CHECK OPTION可更新子句。我们来看下WITH CHECK OPTION可更新子句的语法结构:
CREATE OR REPLACE VIEW view_name AS select_statement WITH CHECK OPTION;
我们要注意,将分号(;)放在WITH CHECK OPTION子句的末尾,而不是在select语句的末尾来定义视图。完事我们来尝试根据employees表创建一个名为vps的视图,以显示其职位为VP的员工,例如VP Marketing和 VP Sales:
CREATE OR REPLACE VIEW vps AS SELECT employeeNumber, lastname, firstname, jobtitle, extension, email, officeCode, reportsTo FROM employees WHERE jobTitle LIKE '%VP%';
接下来,我们使用以下语句从vps视图中查询数:
mysql> SELECT * FROM vps;+----------------+----------+-----------+--------------+-----------+----------------------+------------+-----------+| employeeNumber | lastname | firstname | jobtitle | extension | email | officeCode | reportsTo |+----------------+----------+-----------+--------------+-----------+----------------------+------------+-----------+| 1056 | Hill | Mary | VP Sales | x4611 | mary.hill@yiibai.com | 1 | 1002 || 1076 | Firrelli | Jeff | VP Marketing | x9273 | jfirrelli@yiibai.com | 1 | 1002 |+----------------+----------+-----------+--------------+-----------+----------------------+------------+-----------+2 rows in set
因为vps是一个简单的视图,因此它是可更新的,所以,我们通过vps视图将一行员工数据信息插入:
INSERT INTO vps(employeeNumber,firstname,lastname,jobtitle,extension,email,officeCode,reportsTo)values(1703,'Lily','Bush','IT Manager','x9111','lilybush@yiiibai.com',1,1002);
我们要注意,新创建的员工通过vps视图不可见,因为她的职位是IT经理,而不是VP。使用以下SELECT语句来验证它:
SELECT * FROM employees WHERE employeeNumber=1703;
执行上面语句,得到以下结果:
+----------------+-----------+-----------+-----------+-----------------------+------------+-----------+----------------------+| employeeNumber | lastName | firstName | extension | email | officeCode | reportsTo | jobTitle |+----------------+-----------+-----------+-----------+-----------------------+------------+-----------+----------------------+| 1703 | Bush | Lily | x9111 | lilybush@yiiibai.com | 1 | 1002 | IT Manager || 1702 | Gerard | Martin | x2312 | mgerard@gmail.com | 4 | 1102 | Sales Rep || 1625 | Kato | Yoshimi | x102 | ykato@gmail.com | 5 | 1621 | Sales Rep || 1621 | Nishi | Mami | x101 | mnishi@gmail.com | 5 | 1056 | Sales Rep |
但这可能不是我们想要的,因为通过vps视图暴露VP员工,而不是其他员工,所以,为了确保视图的一致性,用户只能显示或更新通过视图可见的数据,则在创建或修改视图时使用WITH CHECK OPTION:
新闻热点
疑难解答