• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SQL查询把表起别名要点

武飞扬头像
PHP中文网
帮助31

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanfecjk
系列文章
更多 icon
同类精品
更多 icon
继续加载