(1).第一类:create view v as select * from table;
(2).第二类:create view v as select id,name,age from table;
(3).第三类:create view v[vid,vname,vage] as select id,name,age from table;
如果涉及到数据量过大,业务逻辑需要跨表查询等等也可建立一个跨表的视图,有三种情况:
一、基于同一数据库
这种情况较为简单,只需简单的一行sql命令,如下:
create view v as (select * from table1) union all (select * from table2);
二、基于不同数据库
这种情况只比上面的sql语句多一个数据库的名字,如下:
create view 数据库1.v as (select * from 数据库1.table1) union all (select * from 数据库2.table2);
或
create view 数据库2.v as (select * from 数据库1.table1) union all (select * from 数据库2.table2);
如果执行第一个sql将在数据库1下建立视图,反之亦然;
三、基于不同服务器
这种情况稍微麻烦一点,需要先建立一个远程表来访问远程服务器的数据表,然后再对这个刚建立的远程表和本地表进行视图,步骤如下:
1、查看MySql是否支持federated引擎
(1).登录Mysql;
(2).mysql>show engines;
(3).如果显示为no,在配置文件中添加:federated (在my.ini),重新启动mysql服务。
2、创建远程表
mysql>CREATE TABLE federated_table (
id INT(20) NOT NULL AUTO_INCREMENT,
name VARCHAR(32) NOT NULL DEFAULT '',
other INT(20) NOT NULL DEFAULT '0',
PRIMARY KEY (id)
)
ENGINE=FEDERATEDDEFAULT
CHARSET=utf8
CONNECTION='mysql://fed_user@remote_host:9306/federated/test_table';
CONNECTION可以按如下方式进行配置:
(1).CONNECTION='mysql://username:password@hostname:port/database/tablename'
(2).CONNECTION='mysql://username@hostname/database/tablename'
(3).CONNECTION='mysql://username:password@hostname/database/tablename'
3、建立视图
create view 本地数据库.v as (select * from 本地数据库.table1) union all (select * from 远程数据库.test_table);
落霞与孤鹜齐飞,秋水共长天一色。
创建视图语句:
`report_adinfo`
CREATE
/*[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]*/
VIEW `testsql`.`report_adinfo`
AS
(SELECT u.id AS id,u.account AS account,r.name AS rolename, d.simplename AS simplename,GROUP_CONCAT(m.name) AS menuname
FROM
sys_user AS u,
sys_role AS r,
sys_relation AS rm,
sys_menu AS m,
sys_dept AS d
WHERE
u.roleid = r.id
AND u.deptid = d.id
AND r.id = rm.roleid
AND rm.menuid = m.id
GROUP BY id
);