1. 创建两个表格
CREATE TABLE t1 ( id INT PRIMARY KEY, name VARCHAR(50), age INT ); CREATE TABLE t2 ( id INT PRIMARY KEY, gender VARCHAR(10), city VARCHAR(50) );
2. 向表格中插入数据
INSERT INTO t1 VALUES (1, 'Tom', 25), (2, 'Lucy', 30), (3, 'John', 28); INSERT INTO t2 VALUES (1, 'Male', 'Beijing'), (2, 'Female', 'Shanghai'), (3, 'Male', 'Guangzhou');
3. 创建视图
CREATE VIEW v_join AS SELECT t1.id, t1.name, t1.age, t2.gender, t2.city FROM t1 LEFT JOIN t2 ON t1.id = t2.id UNION SELECT t1.id, t1.name, t1.age, t2.gender, t2.city FROM t2 LEFT JOIN t1 ON t2.id = t1.id;
上述代码中,通过 UNION 将两个表格的左连接和右连接汇总,从而完成全连接的操作。如果需要使用更多的表格进行全连接时,可以将上述操作类比,不断将对应的表格连接进视图中即可。