您的位置:首页技术文章

sql查询给表起别名要点小结(涉及嵌套查询)

【字号: 日期:2023-03-08 16:57:07浏览:3作者:猪猪
目录
  • 可以通过空格或者as给表起别名
  • 简单查询中使用别名
  • 复杂查询中使用别名
  • 总结

可以通过空格或者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新表,编译会显示表或视图不存在错误。

总结

到此这篇关于sql查询给表起别名要点(涉及嵌套查询)的文章就介绍到这了,更多相关sql查询给表起别名内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

标签: Oracle