数据库MySQLⅢ

目录

 

一、连接查询

1 内连接

2 左连接

3 右连接

二、子查询


一、连接查询

当查询结果的列来源于多张表时,需要将多张表连接成一个大额数据表,再选择合适的列返回

  • 内连接:查询的结果为两个表匹配到的数据

  • 左连接:查询的结果为两张表匹配到的数据加左表特有的数据,对于右表中不存在的数据用null填充

  • 右连接:查询的结果为两张表匹配到的数据加右表特有的数据,对于左表中不存在的数据用null填充
-- 三表连接  A B C
-- 原理
1. A表和B表 两表连接,产生结果AB(看做一张表)
2. AB和C表连接, 产生结果ABC。

-- 三表连接 students  scores courses

-- 练习
select * 
from students st
inner join scores sc on st.studentno=sc.studentno
inner join courses co on co.courseNo=sc.courseNo;

1 内连接

select * from 表1

inner join 表2 on 表1.列=表2.列

内连接的另外一种语法:

select * from 列1,列2 where 表1.列=表2.列

2 左连接

select * from 表1

left join 表2 on 表1.列=表2.列

3 右连接

select * from 表1

right join 表2 on 表1.列=表2.列

二、子查询

在一个select语句中,嵌入另外一个select语句,那么,嵌入的select语句称之为子查询语句,外层的select称之为主查询语句

主查询和子查询的关系:

  • 子查询是嵌入到主查询中
  • 子查询是辅助主查询的,要么充当条件,要么充当数据源
  • 子查询是可以独立存在的语句,是一条完整的select语句

子查询结果:

a. 标量子查询:具体某个值(一行一列)

b. 列子查询:一列数据(一列多行)

      select * from scores where studentNo in (select studentNo from students where age=18)

c. 行子查询:一行(一行多列)

              select * from students where (class,age)=(select class,age from students where name = ‘王昭君’)

d. 表级子查询:多行多列(相当于一个表)

       select * from scores s

       inner join (select * from courses where name in (‘数据库','系统测试')) c

       on s.courseNo = c.courseNo

子查询中特定关键字作用:

  • in

主查询 where 列 in (列子查询)

  • any|some 任意一个

主查询 where 条件 列 = any (列子查询)

在条件查询的结果中匹配任意一个即可,等价于in

  • all​​​​​​​

​​​​​​​主查询 where 列 = all(列子查询):等于里面所有

​​​​​​​主查询 where 列 <>all(列子查询):不等于其中所有

发布了8 篇原创文章 · 获赞 1 · 访问量 294

猜你喜欢

转载自blog.csdn.net/qq_36985354/article/details/104193726