SQL(1) 语句

数据操纵I:检索操作
Select S#,Status from S where CITY='paris'
sql select语句最常用形式---‘select <指定字段> from <指定表> where<指定条件>’
列出供应的所有零件的零件号
select P# from sp
结果中零件号重复出现。要消除重复,必须在Select 语句中使用distinct ,见下例。
select distinct P# from sp
select P# ,weight *454 from p;
select子句(还有where子句)既可以包含简单字段名和算术表达式,也可以包含简单常数
select P#,‘weight in grams=’, weight* 454 from P;

如果weight=0 则weight * 454 等于0 对于任何算术表达式 只要它的任意操作数为空,其值也随之为空。
如:weight +454 、weight-454、 weight*454、 weight/454

条件检索 求居住在巴黎且状态》20的供应者号
select S# from s where City='paris' and status>20
where后面的条件或谓词可以包括比较运算符 = >= <= != 布尔运算符and or not 以及指明顺序的括号等。

带顺序的检索
求居住在巴黎的供应者编号及状态,并使结果按状态的降序排列
select S#,status from s where City='paris' order by status desc
order by 子句中,也可以用“列号”代替‘列名’,在这里“列号”指的是结果列的顺序(从左到右)
egg: select P# ,weight*454 from p order by 2,1
首先按重量(以克为单位)的升序排列,然后在此基础上再按零件号升序排列

使用between检索
求重量范围在16到19(包括此二值)之间的零件
select P#,Pname,color,weight,city from p where weight between 16 and 19
select P#,Pname,color,weight,city from p where weight not between 16 and 19

使用in的检索
求重量为12,16或17的零件
select P#,Pname,color,weight,city
from P where in(12,16,17)
in谓词 等价于哥哥比较项用”or“连起来的谓词形式,还用 就是not in

使用LIke 的检索
以字母C起头的零件名称
select P#,pname,color,weight,city
from p where pname like 'C%'
like谓词呈如下形式:
<列名> like <字符串常量>
列名只能是char 或varchar 型的列
常量中符号解释如下
短实线_表示任意单个字符
百分号%表示n个字符的任意序列(其中n也可以是零)
其余字符就代表他们自己

egg address like '%Berkeley%' 如果Address 中任意位置上有串‘berkeley’,则为真
S# like 'S_ _' 如果S# 恰好是3个字符长,且并第一字符是s,则其值为真
Pname lIke '%C_ _ _' 如果pname 等于或大于4个字符长,其中含有字符C 但C不在最后三字字符处,则其值为真
链接查询
简单的连接查询
求处于同一城市的供应者和零件的全部信息组合
select s.*,p.* from s,p where s.City=p.city
where 子句中的字段引用必须由相应表的名字加以限定

1.子查询(subquery)或嵌套select的概念
2.存在Exists 存在量词或连接乃是整个sql语言中最重要和最基本的特征
3.内部函数 Count,sum,Avg等并介绍这些函数group bu和having 子句中的应用
4.UNION算符
简单子查询
给出提供零件p2的供应者名

子查询 select Sname from s where S# in(select S# from sp where P#=‘p2’)
连接查询 select s.sname from s,sp where s.S#=sp.S# and sp.P#=‘p2’

给出至少提供一种红色零件的供应者名

多层嵌套子查询 select sname from s where S# in(select S# from sp where sp.P# in(select P# from p where color='red'))

相关子查询

给出提供零件p2 的供应者名 。为了说明另一种 论题。 我们用另一方法来解决这个问题

select sname from s where 'p2' in (select P# from sp where S# = s.s#)

posted @ 2015-11-05 09:11  郭端阳  阅读(112)  评论(0)    收藏  举报