sql要点

时间:2023-03-08 23:43:47
sql要点
oracle
并操作 union  自动去除重复    如果想保留重复,需要使用union all
交操作intersect  自动去除重复    如果想保留重复,需要使用intersect all
差操作 except 自动去除重复    如果想保留重复,需要使用except all
聚集函数
平均值:avg
最小值:min
最大值:max
总和:sum
计数:count
sum和avg必须是数字
使用group by可以将其作用在一组元组集上。
有时候,对分组限定条件比对元组限定有用,使用having子句。
select count(*)
from customer 计算关系中元组的个数。自动去除重复。
ps:where应在having之前。
空值:可以使用where 。。is (not) null检测空值和非空值。
如果算数运算的一个输入有个为空。则该算数表达式为空。
如果比较运算符有空值作为比较对象,则结果为false。
总而言之:除了count(*)外所有聚集函数都忽略输入中的空值,空值的忽略有可能造成无输入参加函数运算。规定count在无输入的情况下值无0,其他返回空值。
嵌套子查询:子查询是嵌套在另一个查询中的select-from-where表达式。
集合成员测试:连接词in测试集合中的成员。
select distinct customer-name
from borrower
where customer-name in(select customer-name from depositor)
select distinct customer-name
from borrower,loan
where borrower.loan-number=loan.loan-number and branch-name="Perryridge"and
(branch-name,customer-name) in
(select branch-name,customer-name
from depositor,account
where depositor,account-number=account.acount-number)
not in 用法
找出所有在银行中有贷款但无账户的用户。
select distinct customer-name
from borrower
where customer-name not in(select customer-name from depositor) 
in和not in也能用于枚举集合。
集合的比较:
>some ,<some,>=some,<>some
=some等价于in,不过<>some并不等价于not in。在sql中,关键词any同义于some。
>all对应词组“比所有。。。大”
<>all等价于not in
=some等价于in <>all等价于not in
sql中聚集函数不能进行复合。因而max(avg(...))是不允许的。
所以为了找出平均余额最高的分支机构
select branch-name
from account
group by branch-name
having avg(balance)>=all(select avg(balance)
from account group by branch-name)
测试子查询的结果是否有元组。exists结构在作为参数的子查询非空时返回true
select customer-name
from borrower
where exists(select *
                      from despositor
                       where despositor.customer-name=borrower.customer-name)
在一个子查询中,合法的做法是只是用在该子查询中或包含该子查询的查询中定义的元组变量。如果一个元组变量既在子查询中定义,又在包含该子查询的查询中定义,则子查询中的定义有效。
测试是否存在重复的元组
如果作为参数的子查询的结果中没有重复元组,使用unique结构测试将返回true。
删除
delete from account
where branch-name in (select branch-name
from branch
where branch-city="NeedMan")
插入:
insert into account
values("","",1200)
更新:update acoount
set balance=balance*1.06
where balance>10000
关系的连接
内连接:
**表 inner join **表 on 关联条件
左外连接:
左外连接的计算如下:首先计算内连接的结果,然后,对左边关系loan中的每个与右边关系borrower中的任何元组在内连接时都不匹配的元组t,在结果中都加入一个元组r。r的从左边关系中得到的属性值被赋为t中的值,而r的其他属性值被赋值为空。
自然连接:**表 nature inner join **表
和on进行内连接的结果相似。但是关联条件的属性只出现一次。
sql要点
sql-92中每一种连接操作都包含一个连接类型和连接条件。连接条件决定了两个关系中哪些元组相互匹配,以及连接结果中出现哪些属性。连接类型决定了如何处理连接条件不匹配的元组。
外连接,连接条件是必须的,内连接,连接条件是可选的。(如果忽略,将产生笛卡尔乘积)
关键字natural出现在连接类型前面,关键字 on,using出现在连接表达式的末尾。关键字inner和outer是可选的,因为根据连接类型的其余内容可以推断出是内连接还是外连接。
连接条件using(A1,A2,....,An)类似于自然连接的条件,只是连接属性不再是两个关系中所有的公共属性,而是属性A1,A2,...,An.A1,A2,...,An都必须是两边关系中的公共属性,而且在结果关系中只出现一次。
全外连接时左外连接和右外连接
sql中的域类型
sql-92标准支持很多种预定义的域类型,其中包括下列类型:
char(n)为固定长度的字符串。
varchar(n)
int
smallint
numeric(p,d)