凯发真人娱乐

sql 查询 总结 【行子查询 ; 列子查询 ; 表子查询 ; 自链接 ; 内连接 ;外连接 ; 无规则链接 ……】 -凯发真人娱乐

2023-08-17,,

简单介绍一下连接方式:

1.1.使用无连接规则连接两表   

    无限规则  也就简单的 select * from tablea , tableb  即得到一个笛卡尔积。  什么是 笛卡尔积 在 我的 另外一篇文章中

1.2 .使用有连接规则连接两表

    也就是在 上边的基础上 加上 条件 select * from tablea , tableb where  tablea .colom1 = tableb .colom

1.3. 使用多表连接数据

    相对于上边的1.2来说   select * from tablea , tableb,tablec  where  tablea .colom1 = tableb .colom and tablea.pid = tablec.id

二  高级连接查询

2.1 . inner join  下边是 连接语法

select *
from 表名1
inner join 表名2
on 连接规则1
inner join 表名3
on 连接规则 2

2.2自链接查询:

select a.* from `users` as a inner join  `users` as b
where a.user_id = b.user_id

2.3 外连接

  2.3.1 外连接  右外连接  这里只写 一个 右外连接  的同理  【左外连接就是 包含 左边表的所有内容和右边的需要相关联的内容】

select *
from stu_info
right outer join score
on stu_info.sno=score.sno

2.4全外连接

select *
from stu_info
full outer join score
on stu_info.sno=score.sno

2.5 组合查询

这个不多做赘述 主要是因为怕解释不到位 以 union  链接 函数为例子‘

首先简单介绍下 union 的使用方法 详情介绍的看   https://www.runoob.com/mysql/mysql-union-operation.html

select 列名称 from 表名称 union select 列名称 from 表名称 order by 列名称;
select 列名称 from 表名称 union all select 列名称 from 表名称 order by 列名称;
select *
from stu_info
where depart=’外语系’
union
select *
from stu_info
where year>21
## 这个是为了 查询出来 学科为去往 外语系 的 所有 stu—info 的表的数据 并且 从 stuinfo 表中 找到年龄大于21 岁 的 由于用的 是 union 所以说 取 交集

2.6 查询

简单介绍 什么是列子查询  列子查询的常见使用 操作符

列子查询中使用 in、any、some 和 all 操作符

由于列子查询返回的结果集是 n 行一列,因此不能直接使用 = > < >= <= <> 这些比较标量结果的操作符。在列子查询中可以使用 in、any、some 和 all 操作符:

in:在指定项内,同 in(项1,项2,…)。
any:与比较操作符联合使用,表示与子查询返回的任何值比较为 true ,则返回 true 。
some:any 的别名,较少使用。
all:与比较操作符联合使用,表示与子查询返回的所有值比较都为 true ,则返回 true

select s1 from table1 where s1 > any (select s2 from table2)

上边就是一个简单的例子  用的是 any  ;

注意 :not in 是 <> all 的别名,二者相同。

2.7  行子查询
行子查询是指子查询返回的结果集是一行 n 列,该子查询的结果通常是对表的某行数据进行查询而返回的结果集。

select * from article where (title,content,uid) = (select title,content,uid from blog where bid=2)

2.8 表子查询

下边仅仅是个例子 ; 不是现实环境  ;{不会有设计表的 一边算年龄 一边算出生日期 的  }

大致的目的就是 从表中查询出的数据 作为另一个 查询的对象

select  a.* ,b.userpwd , b. date_format(user.birthday, '%y-%m-%d %h:%i:%s')
from (
select tea.id, tea.name ,users.usercz as '成绩',user.userid
,tclass.classname
from teacher as tea ,user, tclass
where tea.id = user.tid
and tclass.id = user.cid
and user.age>20
and user.usertype = '先锋班级'
and tclass.classcode < 2018
) as a inner join user as b
where a.userid = b.userid
and year(now()) - year(birthday()) <50

sql 查询 总结 【行子查询 ; 列子查询 ; 表子查询 ; 自链接 ; 内连接 ;外连接 ; 无规则链接 ……】的相关教程结束。

网站地图