在创建视图时,经常需要使用到MySQL的流程控制语句,如:IF语句和CASE语句。
示例:
创建MySQL视图中使用IF和CASE语句。
-- 判断数据表是否存在,存在则删除 DROP TABLE IF EXISTS tb_staff; -- 创建数据表 CREATE TABLE IF NOT EXISTS tb_staff ( id INT AUTO_INCREMENT PRIMARY KEY COMMENT '编号', NAME VARCHAR(50) NOT NULL COMMENT '姓名', sex INT COMMENT '性别(1:男;2:女;)', dept_code VARCHAR(10) COMMENT '部门编号', is_post BIT COMMENT '是否在职(0:否;1:是)' ) COMMENT = '员工信息表';
-- 新增数据 INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_01',1,'1001',1); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_02',2,'1002',1); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_03',1,'1003',0); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_04',1,'1001',1); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_05',2,'1008',1); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_06',1,'1001',0); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_07',2,'1002',1); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_08',1,'1003',0); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_09',1,'1001',1); INSERT INTO tb_staff(NAME,sex,dept_code,is_post) VALUES('pan_junbiao的博客_10',2,'1008',0);
查询员工信息表结果:
-- 创建视图 CREATE OR REPLACE VIEW view_staff AS SELECT id ,NAME ,IF(sex=1,'男','女') AS sex_name ,CASE dept_code WHEN '1001' THEN '研发部' WHEN '1002' THEN '人事部' WHEN '1003' THEN '财务部' ELSE '其他' END AS dept_name ,IF(is_post,'在职','离职') AS is_post_name FROM tb_staff ;
查询员工视图结果:
以上为个人经验,希望对您有所帮助。