Connection mode in database query

Use two tables (a_table, b_table), the associated fields a_table.a_id and b_table.b_id to demonstrate the inner connection and outer connection of MySQL (left (outer) connection, right (outer) connection, full (outer) connection).

MySQL version: Server version: 5.6.31 MySQL Community Server (GPL)

Database tables: a_table, b_table

Theme: inner connection, left connection (left outer connection), right connection (right outer connection), full connection (full outer connection)

premise

Table building statement:

CREATE TABLE `a_table` (
  `a_id` int(11) DEFAULT NULL,
  `a_name` varchar(10) DEFAULT NULL,
  `a_part` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `b_table` (
  `b_id` int(11) DEFAULT NULL,
  `b_name` varchar(10) DEFAULT NULL,
  `b_part` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Table test data:

1. Internal connection

Keywords: inner join on

语句:select * from a_table a inner join b_table b on a.a_id = b.b_id;

Results of the:

Description: Combine the records in the two tables and return the records that match the associated fields, that is, return the intersection (shaded) part of the two tables.

Second, the left connection

关键字:left join on / left outer join on

语句:select * from a_table a left join b_table b on a.a_id = b.b_id;

Results of the:

Description:

Left join is the abbreviation of left outer join, its full name is left outer join, which is a kind of outer join.

For the left (outer) connection, all the records of the left table (a_table) will be displayed, while the right table (b_table) will only display the records that meet the search criteria. Insufficient places in the table on the right are NULL.

Three, right connection

关键字:right join on / right outer join on

语句:select * from a_table a  right outer join b_table b  on a.a_id = b.b_id;

Results of the:

Explanation:
Right join is the abbreviation of right outer join. Its full name is right outer join, which is a kind of outer join.
Contrary to the left (outer) connection, the right (outer) connection, the left table (a_table) will only display the records that meet the search criteria, and the right table (b_table) will show all the records. Insufficient records in the left table are all NULL.

Four, fully connected

MySQL currently does not support this method, it can be solved by other methods.


Copyright statement: This article is the original article of the CSDN blogger "plg17". It follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/plg17/article/details/78758593

Guess you like

Origin blog.csdn.net/qq_43191910/article/details/114953243