MySQL_6 self-join and outer join

Table of contents

1. Self-connection

        1 Overview: 

        2. Grammar: 

        3. Demo: 

2. Outer connection 

        1. Why do you need an outer join?

        2. Definition of outer connection: 

        3. Demonstration of outer connection: 

                1° left outer join

                2° right outer join

                3° Solution to the department table problem


1. Self-connection

        1 Overview : 

        Self-join refers to a join query on the same table (the same table is regarded as two tables); self-join is essentially a special multi-table query.

        2. Grammar: 

        SELECT column_1 [AS alias_1], column_2 [AS alias_2]...

                FROM table_1 table alias, table_2 table alias...

                WHERE connect_expression...;

        Precautions--

        You can alias the query field according to your needs ;

        When self-joining a table, two aliases must be given to the table, otherwise an error will be reported ; AS is not required when aliasing a table.

        3. Demo: 

                Let’s create a staff table first, as follows——

CREATE TABLE IF NOT EXISTS `staff`(
	`sno` MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
	`sname` VARCHAR(40) NOT NULL DEFAULT '',
	`ssex` CHAR(10),
	`ssalary` DECIMAL(8,2),
	`mgr` MEDIUMINT UNSIGNED NOT NULL DEFAULT 0
) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin ENGINE INNODB;

INSERT INTO `staff`(`sno`,`sname`,`ssex`,`ssalary`,`mgr`)
			VALUES
			(1000,'Cyan','male',15000,500),
			(1001,'Ice','male',17000,501),
			(1002,'Rain','female',20000,502),
			(1003,'Five','female',9900,503),
			(1004,'Rose','female',13500,504),
			(1005,'Wood','male',12700,505),
			(500,'爷1号','male',99999,0),
			(501,'爷2号','male',99999,0),
			(502,'爷3号','male',99999,0),
			(503,'爷4号','male',99999,0),
			(504,'爷5号','male',99999,0),
			(505,'爷6号','male',99999,0);

SELECT * FROM `staff`;

               It is now required
                to query the employee number, employee name, and the corresponding superior number and superior name of the employee. as follows :  

# 相当于把第一张表当作了下属表,第二张表当作了上级表(本质是同一张表)。
SELECT
	`demo_1`.`sno` AS 'sub_no',
	`demo_1`.`sname` AS 'sub_name',
	`demo_1`.`mgr` AS 'sup_no',
	`demo_2`.`sname` AS 'sup_name'
FROM
	`staff` `demo_1`,
	`staff` `demo_2` 
WHERE
	`demo_1`.mgr = `demo_2`.sno;
			


2. Outer connection 

        1. Why do you need an outer join?

        In the multi-table query , the Cartesian product results are filtered by the conditions of the WHILE clause; however, the query results will only display the records that match the WHERE association conditions successfully, not the records that fail to match .

                For example, there are currently two tables, employee table emp and department table dep , as shown in the following figure: 

                It is now required
                to query the employee's name, employee position, employee department number and corresponding department name, and if there is no employee under a certain department, the department number and department name are also required to be displayed.

SELECT ename,ecareer,emp.deptno,dname
		FROM emp,dep
		WHERE emp.deptno = dep.dno;

                Obviously, ordinary multi-table queries cannot meet our needs. This is because there are no employees in the 40 department in the employee table, so the association conditions of the WHERE clause are not satisfied, and the multi-table query will only display records matching the conditions of the WHERE clause, so the department number and department of the 40 department cannot be displayed Name, but 40 departments do exist, which is a disadvantage of multi-table query.

        2. Definition of outer connection: 

        There are two most commonly used outer joins, left outer join and right outer join. Among them, the left outer join means that the table on the left will be completely displayed after the join ; the right outer join means that the table on the right will be completely displayed after the join .

        The left outer join format is as follows:

                SELECT column_1, column_2...column_n

                        FROM table_1 LEFT JOIN table_2

                        ON connect_expression;

        The right outer join format is as follows -

                SELECT column_1, column_2...column_n

                        FROM table_1 RIGHT JOIN table_2

                        ON connect_expression;

        Note -
        After the left outer join, the records that cannot match the query conditions in the left table will also be displayed, but the field data that does not exist in the left table will automatically be NULL; after the right outer join, the records that cannot match the query conditions in the right table will also be displayed. will be displayed, but the field data that does not exist in the right table is automatically NULL.

        3. Demonstration of outer connection: 

                1° left outer join

                Let's build two tables first - the student table stus and the grade table scores.
                The code to create the student table stus is as follows: 

CREATE TABLE IF NOT EXISTS `stus`(
	`id` MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
	`name` VARCHAR(32) NOT NULL DEFAULT '',
	`sex` CHAR(16) NOT NULL DEFAULT ''
) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin ENGINE INNODB;

INSERT INTO `stus`(`id`, `name`, `sex`)
		VALUES
		(1, 'Cyan', 'male'),
		(2, 'Five', 'female'),
		(3, 'Ice', 'male'),
		(4, 'Rain', 'female'),
		(5, 'Kaiyu', 'male');
		
SELECT * FROM `stus`;

                The effect of student table stus is as follows: 

                The code to create the grade table scores is as follows: 

CREATE TABLE IF NOT EXISTS `scores`(
	`id` MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
	`score` MEDIUMINT UNSIGNED NOT NULL DEFAULT 0
) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin ENGINE INNODB;

INSERT INTO `scores`
		VALUES
		(1, 141),
		(2, 135),
		(5, 142),
		(7, 138),
		(10, 150);
		
SELECT * FROM `scores`;
		

               The results of the score table are as follows:         

                It is now required
                to query the student's number, name and grades; and to display all the students. If the student has no grades, the grade column will be displayed as empty.

SELECT stus.id, `name`, score
		FROM stus LEFT JOIN scores
		ON stus.id = scores.id;

                2° right outer join

                Still operate the student table stus and the grade table scores,
                and now require -
                request to query the student's number, name, gender and grades; and request to display all grades, if there is no corresponding student in the student table, the relevant information of the student will be displayed as empty .

SELECT stus.id, `name`, sex, score
		FROM stus RIGHT JOIN scores
		ON stus.id = scores.id;

                3° Solution to the department table problem

                For the problem of displaying all departments raised in "Why Outer Join is Needed", it can now be solved through Left Outer Join and Right Outer Join.
                The requirements are as follows -
                query the employee's name, employee position, employee department number and corresponding department name, and if there is no employee under a certain department, it is also required to display the department number and department name
                code as follows: 

# 方式一 : 左外连接
SELECT ename,ecareer,dep.dno,dname
		FROM dep LEFT JOIN emp
		ON dep.dno = emp.deptno;
		
# 方式二 : 右外连接
SELECT ename,ecareer,dep.dno,dname
		FROM emp RIGHT JOIN dep
		ON emp.deptno = dep.dno;

        System.out.println("END------------------------------------------------------------------------------"); 

Guess you like

Origin blog.csdn.net/TYRA9/article/details/130742132