首页 > 编程知识 正文

SQL查询概念,sql查询有多少种

时间:2023-05-04 14:45:16 阅读:260135 作者:1174

几种表的查询 自连接查询
在一张表中,单纯地使用select语句并加上where条件进行查询,得到的只是列与列之间存在的关系
例如此表:

查询语句:select 本月,累计 from test where 本月>累计
得到如下图的查询结果

可是,如果我们想要查询当累计数值都为负数时,本月数据不相等的两个地区有多少种可能,这要怎么查询?显然单纯地使用select是无法解决的,因为这个查询问题已经涉及到了列中数据与数据之间的关系
查询语句:select first.地区 second.地区 from data_fu first,data_fu second where first.本月>second.本月 and first.累计<0 and second.累计<0

自连接的另一个例子:
现有如下的一个表(列车车次和停靠站点):

先要查询出某一线路的火车可以联通的任意两个城市的名称
查询语句:select first.num,first.stop as start,second.stop as end from route first,route second where first.num=second.num and first.stop!=second.stop;
查询结果:

交叉连接(cross join)
交叉连接的效果就是两个表的广义笛卡尔积
查询语句:select s.* , teacher_name from student_table s cross join teacher_table t 自然连接(natural join)
给定关系R和关系S,自然连接由R和S的笛卡尔积中选取相同属性组B上值相等的元素构成(自然连接会以两个表中的同名列作为连接条件;如果两个表中没有同名列,则自然连接和交叉连接效果完全一样)
现有两个表:

查询语句:select R.*,S.* from R natural join S
查询结果:

using连接
与自然连接类似,都是以两笔中的同名列作为连接条件,但是,区别在于,若两表中有多个同名列,使用using子句可以显式指定以哪个同名列作为连接条件
查询语句:select s.*,teacher_name from student_table s join teacher_table t using(teacher_id) on连接
可以替代用where引出的等值连接和非等值连接
查询语句:select s.*,teacher_name from student_table s join teacher_table t on s.java_teacher=t.teacher_i 左外连接和右外连接
左外连接:用左表的数据去匹配右表,不符合条件的数据用NULL代替
例如:有如下两表:

左外连接:
查询语句:select s.*,teacher_name from student s left join teacher t on s.java_teacher>t.teacher_id;
查询结果:

这里用s表匹配t表,(一共会匹配10次,结果会剔除重复的数据),当左表无法与右表成功匹配时,保留左表中的数据,补null

右外连接:与左外连接相反
查询语句select s.*,teacher_name from student s right join teacher t on s.java_teacher<t.teacher_id;
查询结果:

右表数据保留,补null
<左外连接,结果里必须有左表里的全部数据,右外连接相反>

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。