mysql 聯合表(federated)及檢視
1)驗證環境
源庫:192.168.8.75 centos 7.5 mysql8.3
目標庫:192.168.8.68 redhat 6.8 mysql5.7
2)登入源庫並建立源表
$ mysql -u root -ppaasword -h 192.168.8.75
mysql> create database db_test;
mysql> use db_test;
mysql> create table t1(c1 int,c2 char(100));
mysql> insert into t1 values(1,'a');
3)登入源庫建立使用者並授權
$ mysql -u root -ppaasword -h 192.168.8.75
mysql> create user test@'%' identified by 'password';
mysql> grant select,insert,delete,update on db_test.t1 to test@'%';
3)目標庫啟用聯合引擎
# vi /etc/my.cnf#新增如下行並儲存
federated
# service mysqld start
4)登入目標庫並建立聯合表
# mysql -u root -ppassword -h 192.168.8.68
mysql> create database db_test;
mysql> use db_test;
mysql> create table f_t1(c1 int,c2 char(100))) engine=federated connection ='mysql://user_test:[email protected]:3306/test/t1';
5)登入目標庫建立使用者並授權
$ mysql -u root -ppassword -D db_test -h 192.168.8.68
mysql> create user test@'%' identified by 'password';
mysql> grant select,insert,delete,update on test.f_t1 to test;
5)登入目標庫test使用者測試
$ mysql -u test -ppassword -D db_test -h 192.168.8.68
mysql> select * from f_t1;
mysql> insert into f_t1 values(2,'b');
mysql> delete from f_t1 where c1=1;
mysql> update f_t1 set c2='w' where c1=2;
6)登入源庫刪除源表
$ mysql -u root -ppassword -D db_test -h 192.168.8.75
mysql>drop table t1;
7)登入目標端再次操作聯合表
$ mysql -u user_test -ppassword -D db_test -h 192.168.8.68
mysql> select * from f_t1;
--會報錯error 1430。
8)登入源庫重建源表
$ mysql -u root -ppassword -D db_test -h 192.168.8.75
mysql> create table t1(c1 int,c2 char(100));
mysql> insert into t1 values(3,'cc');
9)再次登入目標庫並操作聯合表
$ mysql -u user_test -ppassword -D db_test -h 192.168.8.68
mysql> select * from f_t1;
mysql> insert into f_t1 values(5,'e');
--現在聯合表一切恢復正常,可見源表刪除並不會影響目標庫中聯合表的定義,重建源表即可恢復正常。
10)登入目標庫建立檢視
$ mysql -u user_test -ppassword -D db_test -h 192.168.8.68
mysql> create view v_f_t1 as select * from f_t1 where c1<5;
mysql> select * from v_f_t1;
--可見檢視可以基於聯合表建立。
mysql> insert into f_t1 values(6,'f');
mysql> select * from v_f_t1;
--可見檢視可以限制使用者對資料的訪問範圍。
mysql> insert into v_f_t1 values(7,'h');
--可見檢視並不能限制使用者插入資料的範圍,其實,不僅針對聯合表,針對常規表的檢視,也是這樣。
mysql> update v_f_t1 set c2='w';
--可見檢視可以限制使用者對資料集的更改範圍,使用者只能更改檢視定義中允許範圍的資料,哪怕update語句不帶任何where條件。
mysql> delete from v_f_t1;
--可見檢視可以限制使用者對資料集的刪除範圍,使用者只能刪除檢視定義中允許範圍的資料,哪怕delete語句不帶任何where條件。