MySQL table join query basics

First, the use of table join query

When you need to display the fields of multiple tables at the same time, you can use table join to achieve such a function. Table joins are divided into inner joins and outer joins. Inner joins select only the records that match each other in the two tables, while outer joins select other records that do not match.

2. Examples

The following two tables are examples:

Table name: teacher_table
write picture description here

Create table statement:

create table teacher_table(
    teacher_id int not null auto_increment primary key,
    teacher_name varchar(20),
    phone_number varchar(20),
);

Table name: student_table
write picture description here
Create table statement:

create table student_table(
    id int not null auto_increment primary key,
    name varchar(20),
    teacher int,
    foreign key(teacher) references teacher_table(teacher_id) on 
        delete set null on update cascade
    );

1. Inner connection example

The syntax of the table join query statement is as follows:

select column1,column2... 
from table1,table2...
[where condition];

Among them, column is the name of the column to be queried, and table is the table to be referenced.
If you have the same column names in two tables, you need to use a table alias prefix or table name prefix as a restriction between these same-named columns to avoid confusion.

example:

select 
    name,teacher_name 
from 
    teacher_table t,student_table s 
where 
    s.teacher = t.teacher_id;

Results of the:
write picture description here

2. Outer connection

Outer joins are divided into left outer joins and right outer joins, which are specifically defined as:

Left join: Include all records in the left table even if there are no records in the right table that match it.
Right join: Include all records in the right table even if there are no records in the left table that match it.

Left join query example:

select 
    teacher_name,name 
from 
    teacher_table t left join student_table s 
on 
    t.teacher_id = s.teacher;

search result:
write picture description here

The right join is similar to the left join, and the two can be converted to each other. For example, the above example can be rewritten as:

select 
    teacher_name,name 
from 
    student_table s  right join teacher_table t
on 
     s.teacher = t.teacher_id;

The query result is the same as above

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326030129&siteId=291194637