mysql

Mysql

内连接、外连接

  • 创建一个学生表
create table students
(
    id int primary key auto_increment,
    name varchar(100)
);
  • 创建一个成绩表
create table scores
(
   scoreId int primary key auto_increment,
   stuId int not null,
   math double
);
  • 给 两张表插入数据
insert into students values(null, "smx");
insert into students values(null, "xyj");
insert into students values(null, "wdd");
insert into students values(null, "hhr");

insert into scores values(null, 1, 100);
insert into scores values(null, 2, 99);
insert into scores values(null, 3, 98);
insert into scores values(null, 5, 97);
image.png

image.png
  • 内连接
select * from students as stu inner join scores as s on stu.id = s.stuId; # 内连接
select * from students as stu join scores as s on stu.id = s.stuId; # 内连接
image.png
  • 左连接
    select * from students as stu left join scores as s on stu.id = s.stuId; # 左连接

    image.png

  • 右连接
    ``select * from students as stu right join scores as s on stu.id = s.stuId; # 右连接


    image.png
  • 外连接
select * from students as stu left join scores as s on stu.id = s.stuId
union
select * from students as stu right join scores as s on stu.id = s.stuId;  # mysql没有全外连接的实现,只能自己手动实现,取左连接和右连接的并集
image.png

你可能感兴趣的:(mysql)