教您如何实现MySQL动态视图


  本文标签:MySQL动态视图

  MySQL动态视图的实现方法应该是我们都需要掌握的,下面就教您如何实现MySQL动态视图的方法,希望对您能够有所帮助  。

  用户为C/S结构,每个用户根据角色不同,能看到不同的数据  。系统会根据某个标识生成一个数据内容,然后通过统一的视图来访问  。

  需求:

  用户为C/S结构,每个用户根据角色不同,能看到不同的数据  。系统会根据某个标识生成一个数据内容,然后通过统一的MySQL动态视图来访问  。

  要求,不能修改MySQL动态视图,也不能在试图外面再嵌套一层查询  。

  设计:

  系统通过某种方法生成一个唯一的ID(可以是应用端,也可以是数据库的uuid),然后将试图与这个id进行关联即可  。

  代码:
 

  1. drop table if exists test;   
  2. create table test (   
  3. id int not null,   
  4. name varchar(20) not null   
  5. );   
  6. insert into test values(1,test1);   
  7. insert into test values(1,test11);   
  8. insert into test values(1,test111);   
  9. insert into test values(2,test2);   
  10. insert into test values(2,test22);   
  11. drop function if exists getSpid;   
  12. delimiter |   
  13. CREATE function getSpid()   
  14. RETURNS int   
  15. RETURN @spid;   
  16. |   
  17. delimiter ;   
  18. drop view if exists v_test;   
  19. create view v_test as   
  20. select * from test where id=getSpid();   
  21. -- 测试代码   
  22. -- 开启session 1   
  23. set @spid=1;   
  24. select * from v_test;   
  25. -- 开启session 2   
  26. set @spid=2;   
  27. select * from v_test; 

  说明:

  将生成的ID保持到session变量里面

  然后建立自定义函数,返回这个变量

  最后在MySQL动态视图里面调用这个函数