MySQL动态视图的实现方法应该是我们都需要掌握的,下面就教您如何实现MySQL动态视图的方法,希望对您能够有所帮助 。
用户为C/S结构,每个用户根据角色不同,能看到不同的数据 。系统会根据某个标识生成一个数据内容,然后通过统一的视图来访问 。
需求:
用户为C/S结构,每个用户根据角色不同,能看到不同的数据 。系统会根据某个标识生成一个数据内容,然后通过统一的MySQL动态视图来访问 。
要求,不能修改MySQL动态视图,也不能在试图外面再嵌套一层查询 。
设计:
系统通过某种方法生成一个唯一的ID(可以是应用端,也可以是数据库的uuid),然后将试图与这个id进行关联即可 。
代码:
- drop table if exists test;
- create table test (
- id int not null,
- name varchar(20) not null
- );
- insert into test values(1,test1);
- insert into test values(1,test11);
- insert into test values(1,test111);
- insert into test values(2,test2);
- insert into test values(2,test22);
- drop function if exists getSpid;
- delimiter |
- CREATE function getSpid()
- RETURNS int
- RETURN @spid;
- |
- delimiter ;
- drop view if exists v_test;
- create view v_test as
- select * from test where id=getSpid();
- -- 测试代码
- -- 开启session 1
- set @spid=1;
- select * from v_test;
- -- 开启session 2
- set @spid=2;
- select * from v_test;
说明:
将生成的ID保持到session变量里面
然后建立自定义函数,返回这个变量
最后在MySQL动态视图里面调用这个函数