Mysql 之 join 体验

1 创建表

CREATE TABLE `table_a` (
  `id` varchar(32) DEFAULT NULL COMMENT '主键',
  `name` varchar(32) DEFAULT NULL COMMENT '姓名',
  `code` varchar(32) DEFAULT NULL COMMENT '编码'
) ENGINE=InnoDB DEFAULT CHARSET=gb2312 COMMENT='测试表A ';

CREATE TABLE `table_b` (
  `id` varchar(32) DEFAULT NULL COMMENT '主键',
  `name` varchar(32) DEFAULT NULL COMMENT '姓名',
  `code` varchar(32) DEFAULT NULL COMMENT '编码'
) ENGINE=InnoDB DEFAULT CHARSET=gb2312 COMMENT='测试表B ';

2 初始化数据

INSERT INTO `sql_optimize_demo`.`table_a` (`id`, `name`, `code`) VALUES ('1', '小A', 'A');
INSERT INTO `sql_optimize_demo`.`table_a` (`id`, `name`, `code`) VALUES ('2', '小B', 'B');
INSERT INTO `sql_optimize_demo`.`table_a` (`id`, `name`, `code`) VALUES ('3', '小C', 'C');
INSERT INTO `sql_optimize_demo`.`table_a` (`id`, `name`, `code`) VALUES ('4', '小D', 'D');
INSERT INTO `sql_optimize_demo`.`table_a` (`id`, `name`, `code`) VALUES ('5', '小E', 'E');
INSERT INTO `sql_optimize_demo`.`table_b` (`id`, `name`, `code`) VALUES ('1', '小A', 'A');
INSERT INTO `sql_optimize_demo`.`table_b` (`id`, `name`, `code`) VALUES ('2', '小B', 'B');
INSERT INTO `sql_optimize_demo`.`table_b` (`id`, `name`, `code`) VALUES ('3', '小C', 'C');
INSERT INTO `sql_optimize_demo`.`table_b` (`id`, `name`, `code`) VALUES ('4', '小F', 'F');
INSERT INTO `sql_optimize_demo`.`table_b` (`id`, `name`, `code`) VALUES ('5', '小G', 'G');

3  连接查询

Oracle 、DB2、SQL Server、PostgreSQL 支持 Full JOIN 但是 MySQL 是不支持的。 可以通过 LEFT JOIN + UNION + RIGHT JOIN 的方式 来实现。

3.1 left join ..

select * from table_a a left join table_b b on a.`code` = b.`code`;


3.2 right join ...

select * from table_a a right join table_b b on a.`code` = b.`code`;

 


3.3 inner join ... 

select * from table_a a inner join table_b b on a.`code` = b.`code`;


 3.4 left join ...where ... is null

select * from table_a a left join table_b b on a.`code` = b.`code` where b.`code` is null;

 


3.5 right join ...where ... is null

select * from table_a a right join table_b b on a.`code` = b.`code` where a.`code` is null;

 


3.6 full outer join ... 

 

方式1:

select * from table_a a  full outer join table_b b on a.`code` = b.`code`;

方式2:

select * from table_a a left join table_b b on a.code = b.code 
union 
select * from table_a a right join table_b b on a.code = b.code ;


  3.7 full outer join ...  where ...

方式1;
select * from table_a a  full outer join table_b b on a.`code` = b.`code` where a.`code` is null or  b.`code` is null;

方式2:
select * from table_a a left join table_b b on a.code = b.code  where b.`code` is null 
union 
select * from table_a a right join table_b b on a.code = b.code  where a.`code` is null

 

猜你喜欢

转载自blog.csdn.net/iss_jin/article/details/121655824