sql查询给表起别名

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

sql查询给表起别名

foas9we   2022-09-29 我要评论

可以通过空格或者as给表起别名

但是注意如果操作的数据库是Oracle的话,只能使用空格,as不符合Oracle的语法。

举个栗子

简单查询中使用别名

select *
from student s
where s.id = '10';

在简单的查询中使用别名,一般没有特别需要注意的地方,要做的操作少

复杂查询中使用别名

题目概要:有三个表格,student(sno,sname,ssex,sbirthday,class)

score(sno,cno,degree)

course(cno,cname,tno)

查询选修“3-105”课程的成绩高于“109”号同学成绩的所有同学的记录。

答案:

select *
 from (select s.sno,s.sname,s.ssex,s.sbirthday,s.class,    sc.degree,c.cno,c.cname,c.tno from student s , course c ,score sc where s.sno = sc.sno and c.cno = sc.cno) ss
 where  ss.cno = '3-105' and ss.degree >( select degree from score where sno = '109' and cno = '3-105');

可以看到,为了方便操作,我们重新定义了一个表格ss,这个表格是一个大表格同时包含了,以上三个表中的内容。但是要注意以下几点,不然容易出错

要全部显示新定义表格的值时,不能直接使用*

比如声明的答案中如果改为

select *
 from (select * from student s , course c ,score sc where s.sno = sc.sno and c.cno = sc.cno) ss
 where  ss.cno = '3-105' and ss.degree >( select degree from score where sno = '109' and cno = '3-105');

命令行会显示列未明确定义,因为我们要现在指定的列作为一个新的表,但是有些列的列名是重复的,我们需要指定其中的一个。

在嵌套查询语句中无法使用新创的表,因为嵌套查询里面的代码是一个完整的执行段,会从头开始运行?反正在里面调用会报错

select *
 from (select * from student s , course c ,score sc where s.sno = sc.sno and c.cno = sc.cno) ss
 where  ss.cno = '3-105' and ss.degree >( select degree from ss where sno = '109' and cno = '3-105');

这段SQL里面在where里面的子查询使用了ss新表,编译会显示表或视图不存在错误。

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们