mysql_多表2

一、建表

  1. 建表并插入数据 student1
    create table student1(
    stu_no int,
    stu_name varchar(10),
    sex char(1),
    age int(3),
    edit varchar(20))
    DEFAULT charset=utf8;
    insert into student1 values
    (1,'wang','男',21,'hello'),
    (2,'小明','女',22,'haha2'),
    (3,'hu','女',23,'haha3'),
    (4,'li','男',25,'haha4');

  2. 建表并插入数据 course
    create table course(
    c_no int,
    c_name varchar(10)
    )
    DEFAULT charset=utf8;
    insert into course values
    (1,'计算机原理'),
    (2,'java'),
    (3,'c'),
    (4,'php'),
    (5,'py');

  3. 建表并插入数据 sc
    create table sc(
    sc_no int,
    stu_no int,
    c_no int,
    score int(3))
    DEFAULT charset=utf8;
    insert into sc values
    (1,1,1,80),
    (2,2,2,90),
    (3,2,1,85),
    (4,2,3,70),
    (5,2,4,95),
    (6,2,5,89);

二、分析

  • 学生表:student1【学生学号,姓名,性别,年龄,编号】
  • 课程表:course【课程编号,课程名称】
  • 选课表:sc【选课编号,学生学号,课程编号,成绩】
  • 关联关系:都和sc表有关系
    • course.课程编号=sc.课程编号
    • student1.学生学号=sc.学生学号

三、三表连接

  1. 先连接2个表,再和第3个表连接
  • 2表连接:select a.*,b.sc_no,b.c_no,b.score from student1 a inner join sc b on a.stu_no=b.stu_no
  • 连接第3张表:select * from course c inner join ( select a.*,b.sc_no,b.c_no,b.score from student1 a inner join sc b on a.stu_no=b.stu_no )s on c.c_no=s.c_no

备注:有重复列解决方法:显示一个表所有内容,再进行关联

  1. 内连接:select * from 表1 inner join 表2 on 表1.关联字段=表2.关联字段 inner join 表3 on 表2.关联字段=表3.关联字段

  2. 左连接:select * from 表1 left join 表2 on 表1.关联字段=表2.关联字段 left join 表3 on 表2.关联字段=表3.关联字段

  3. 右连接:select * from 表1 right join 表2 on 表1.关联字段=表2.关联字段 right join 表3 on 表2.关联字段=表3.关联字段

  4. 内连接的三表连接:select * from 表1,表2,表3 where 表1.关联字段=表2.关联字段 and 表2.关联字段=表3.关联字段

四、题

  1. 查询选修了“计算机原理”的学生学号和姓名
  • 语句:select a.stu_no,a.stu_name from student1 a inner join sc b on a.stu_no=b.stu_no inner join course c on b.c_no=c.c_no where c.c_name="计算机原理"
  1. 查询“小明”同学选修的课程名称
  • 语句:select c.c_name from student1 a inner join sc b on a.stu_no=b.stu_no inner join course c on b.c_no=c.c_no where a.stu_name="小明"`
  1. 查询选修了5门课程的学生学号和姓名
  • 语句:select a.stu_no,a.stu_name from student1 a inner join sc b on a.stu_no=b.stu_no inner join course c on b.c_no=c.c_no group by a.stu_no having count(a.stu_no)=5
posted @ 2026-09-09 15:48  一只鹿吖  阅读(13)  评论(0)    收藏  举报