MySQL 多表查询

全连接

语法结构

1
select * from 表1,表2 where 表1.公共字段 = 表2.公共字段

知识点

  1. 全连接的连接条件是写在 where 后面的。
  2. 如果有查询条件,在连接条件后面使用 and 把查询条件引出来。
  3. 如果在这个查询语句中,用到了公共字段,那么在公共字段前面必须加上表明。

习题

  1. 查询计算机工程系女学生的学生学号、姓名及成绩。

    1
    2
    3
    4
    select sc.sno,sname,degree from student,sc
    where student.sno = sc.sno
    and ssex = '女'
    and sdept = '计算机工程系';
  2. 查询李新老师所授课程的课程号及开课学期

    1
    2
    3
    4
    select course.cno,cname from course,teaching,teacher
    where course.cno = teaching.cno
    and teaching.tno = teacher.tno
    and tname = '李新'

Join 连接

语法结构

1
select * from 表1 join 表2 on 连接条件 where 查询条件

知识点

  1. join 连接分为内连接和外连接,通常情况下使用内连接即可。
  2. join 连接的连接条件写在 on 后面。
  3. 两张表的连接条件后面可以继续 join 第三张表。

习题

  1. 查询计算机工程系女学生的学生学号、姓名及成绩。

    1
    2
    3
    select sc.sno,sname,degree
    from student join sc on student.sno = sc.sno
    where ssex = '女' and sdept = '计算机工程系';
  2. 查询李新老师所授课程的课程号及课程名。

    1
    2
    3
    4
    select course.cno,cname
    from course join teaching t on course.cno = t.cno
    join teacher t2 on t.tno = t2.tno
    and tname = '李新'