【转】SQL学习(二)
1. SQL中的集合函数
名 称 |
参数类型 |
结果类型 |
描述 |
COUNT SUM AVG MAX MIN |
任意(可以是*) 数值型 数值型 字符型或数值型 字符型或数值型 |
数值型 数值型 数值型 同参数的内容一样 同参数的内容一样 |
出现次数 参数的和 参数的平均值 最大值 最小值 |
注: 在WHERE子句的比较操作中不能出现集合函数,除非它们是出现在子查询的选择列表中
例: select cid from customers
where discnt < (select max(discnt) from customers);
2. SQL中的分组
group by ... having ...通用形式
例:当某个代理商所订购的某样品产品的总量超过1000时,打印出所有满足条件的产品和代理商的ID及这个总量
select pid ,aid, sum(qty) as TOTAL from orders
group by pid,aid
having sum(qty)>1000;
执行过程:
- 首先对from子句中的所有表做笛卡尔积
- 接着删除不满足WHERE子句的行
- 然后根据GROUP BY子句对剩余的进行分组
- 最后求出选择列表中表达式的值
- HAVING子句紧跟在GROUP BY之后但先于对选择列表的表达式的计算
注: HAVING一般情况不会单独出现,一般和GROUP BY一起出现,如果省略了GROUP BY子句,那么HAVING子句将把
整个结果当做一个组来使用
1.ODER BY
order by cid desc 对列cid的值从大到小排列,如果省略desc则从小到大排列
2.CAST
cast以一种类型的值为参数并把它显示的转化为另一种类型
cast (substring(cid from 2 for 3) as integer)
cast (o.qty as char(10))
3. CASE
通用形式:case
when search_conditionl then resulet1
when search_condition2 then resulet2
...
else resul(N+1)
end
例: case when city > 'Al1' then city else 'Atlanta' end
4.BETWEEN谓词
expr1 [NOT] BETWEEN expr2 and expr3
其含义(不考虑NOT)实际上就是:expr2<=expr1 and expr1<=expr3
用between谓词比and链接表达式效率高
5.LIKE谓词
colname [NOT] LIKE val [escape val]
第一个val代表模式串,也可以是一个程序变量
下面列出包括通配符在内的所有可用在模式串中的特殊字符:
模式串中的字符 |
含义 |
下划线(_) 百分号(%) 转义字符 所有其他字符 |
任意单个字符的通配符 包含零个或多个字符的任意序列的通配符 用在需要按字面含义引用的字符之前 代表他们自己 |
例:检索cname值以字母"A"打头的顾客的所有信息
select * from customers where cname like 'A%';
如果要在模式串中按字面意思来引用_,%则用转义字符(escape)\
例:检索cname值以“Tip_”打头并且后面跟着任意个字符的顾客的cid值
select * from customers where cname like 'Tip\_%' escape '\';
6. JOIN
1) inter jion
select cname,city,latiude,longitude
from customers c join cities x on c.city =x.cityname;
2) OUTER JOIN
以下2个表S和T
S T
C A A B
c1 a1 a1 b1
c3 a3 a2 b2
c4 a4 a3 b3
做select * from S full outer join t using(A)
结果为:
C A B
c1 a1 b1
c3 a3 b3
c4 a4 null
null a2 b2
也可以用以下形式实现:
select * from S left join using(A) union select * from S right jion T using (A);
1. INSERT
通用形式:
INSERT INTO tablename [colname {,colname...}]
{VALUES (expr |NULL | Subquery)}
例:1. insert into orders (ordno,month)
values (1107.'aug');
2. insert into swcusts
select * from customers
where city in ('dallas','austin');
2. UPDATE
例:1.update agents set percent=1.1*percent where city='New York';
2.update customers set discnt=1.1*discnt where cid in
(select cid from orders group by cid having sum(dollars)>1000);
3. DELETE
例:1.delete from agents where city ='New York';
2. delete from agents where in
(select aid from orders group by adi having sum(dollars)<600);