文章摘要
这篇文章介绍了在SQL中给表起别名的使用方法,特别是在涉及嵌套查询的情况下需要注意的事项。文章指出,在简单的查询中使用别名较为简单,但在嵌套查询中需要特别注意别名的定义。例如,在Oracle数据库中,只能使用空格而不能使用`AS`关键字。文章还通过一个示例说明了如何通过重新定义一个新表`ss`来解决查询问题,并强调了在嵌套查询中不能使用新定义的表,否则会导致编译错误。文章还提醒,在嵌套查询中使用新表时,需要明确指定列名,避免列名重复的问题。文章最后提到,嵌套查询会在查询执行时从头开始运行,因此不能使用新定义的表来调用子查询。
目录可以通过空格或者as给表起别名简单查询中使用别名复杂查询中使用别名总结
但是注意如果操作的数据库是Oracle的话,只能使用空格,as不符合Oracle的语法。
举个栗子
select *
from student s
where s.id=’10’;
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′);
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′);
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′);
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查询给表起别名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:MySQL中几种常见的嵌套查询详解MySQL嵌套查询实现子查询的方法详解MySQL子查询(嵌套查询)、联结表、组合查询MYSQL子查询和嵌套查询优化实例解析MySQL嵌套查询实例详解mysql嵌套查询和联表查询优化方法SQL嵌套查询总结SQL 嵌套查询的具体使用
© 版权声明
文章版权归作者所有,未经允许请勿转载。

