Objectives: A database tables in database B can join tables.
Environment: Windows system, free installation mysql-5.7.22.
Requirements: a lot of tables in a database, a table by business to a different database, save the necessary relationships between tables.
First, open the FEDERATED engine
Executive order: SHOW ENGINES;
Check the mysql database Federated engine is turned on. Shown below, it is not turned on.
Modify the root folder mysql my.ini file (Linux file system modifications my.cnf): Add a new row, Federated content, as shown below:
Restart MySQL
Execute command again:
SHOW ENGINES;
you can see Federated engine is turned on.
Second, two new databases: A and B
A library table to add a student:
CREATE TABLE student(
id VARCHAR(10) NOT NULL DEFAULT '' COMMENT '主键id',
student_name VARCHAR(10) DEFAULT NULL COMMENT '学生姓名',
school_id VARCHAR(10) NOT NULL DEFAULT '' COMMENT '学校id',
PRIMARY KEY(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='学生表';
B Add a school library table:
CREATE TABLE school(
id VARCHAR(10) NOT NULL DEFAULT '' COMMENT '主键id',
school_name VARCHAR(10) DEFAULT NULL COMMENT '学校名称',
PRIMARY KEY(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='学校表';
Third, the data added to the table
A row of data is added in the database:
id = 1
student_name = 琚建飞
school_id = 1
Adding a line of data in the database B:
id=1
school_name = 廊坊师范
Fourth, the establishment of a remote table in the database A
CREATE TABLE school (
`id` varchar(10) NOT NULL DEFAULT '' COMMENT '主键id',
`school_name` varchar(10) DEFAULT NULL COMMENT '学校名称',
PRIMARY KEY (`id`)
) ENGINE=FEDERATED DEFAULT CHARSET=utf8
COMMENT='学校表-远程表' CONNECTION='mysql://root:root@localhost:3306/b/school';
-- root:root 远程数据库的账号和密码
-- localhost:3306 远程数据库的ip和端口
-- b 远程数据库的名称
-- school 远程数据库的表名称
Fifth, the implementation of join operations
SELECT s.id, s.student_name, sc.school_name
FROM student s JOIN school sc ON s.school_id = sc.id
Result:
Local table and a remote table
- The local table update operations, remote table will be updated simultaneously.
- Delete the local table, the remote table is not deleted.
- Remote table structure changes, the local table is not updated.