MySQL Query advanced knowledge --Join

The article is great, are interested can learn about the original link https://www.cnblogs.com/developer_chan/p/9207687.html

MySQL advanced knowledge (B) - Join query

Preface: This article mainly seven cases in MySQL join statement summarized.


0.5 Preparation

The relationship between the primary join two columns of the table or tables, query data from these tables.

First create two tables: tb_emp (the employee table) and tb_dept (department table) and insert the relevant test data.

1.tb_emp table.

DROP TABLE IF EXISTS `tb_emp`;
CREATE TABLE `tb_emp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `deptid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_tb_emp_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `tb_emp`(name,deptid) VALUES ('jack', '1');
INSERT INTO `tb_emp`(name,deptid) VALUES ('tom', '1');
INSERT INTO `tb_emp`(name,deptid) VALUES ('tonny', '1');
INSERT INTO `tb_emp`(name,deptid) VALUES ('mary', '2');
INSERT INTO `tb_emp`(name,deptid) VALUES ('rose', '2');
INSERT INTO `tb_emp`(name,deptid) VALUES ('luffy', '3');
INSERT INTO `tb_emp`(name,deptid) VALUES ('outman', '14');

 

2.tb_dept table.

DROP TABLE IF EXISTS `tb_dept`;
CREATE TABLE `tb_dept` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `deptname` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `tb_dept`(deptname) VALUES ('研发');
INSERT INTO `tb_dept`(deptname) VALUES ('测试');
INSERT INTO `tb_dept`(deptname) VALUES ('运维');
INSERT INTO `tb_dept`(deptname) VALUES ('经理');

 

Inserted from the table is no corresponding data found outman sector.

1.inner join

NOTE: A represents a left table, B represents a right table, the same below.

inner join: A, B total, which is the intersection.

   

2.left join

left jion: A total of unique + AB (intersection)

   

3.right join

right join: B + AB's unique Total (intersection)

   

4.A Unique

   

NOTE: Referring left join, A unique intersection portion AB just removed.

5.B unique

   

NOTE: Referring right join, B unique to the intersection portion AB just removed.

6.AB all have (union)

   

Since mysql does not support full outer join, so here it is converted by the union. And sets AB: AB intersection + B + A unique unique.

7.A, B unique union

   

A, B and a unique set, corresponding to A, B of AB remove all have a total of (intersection).

to sum up

Here the main usage of 7 in MySQL join statement summarized the main attention MySQL does not support full outer join, so need to be converted deformed, and ultimately achieve the desired effect.


by Shawn Chen, 2018. 6. 21 days, in the morning. 


related information

MySQL advanced knowledge series directory

Guess you like

Origin blog.csdn.net/Hollake/article/details/92839315