SQL基础(一)

SQL

SQL数据定义

基本类型

image.png
如果对char(10)属性存入Avi,则空的七个字符会被空格填入,varchar(10)则不会有空格

用var和char对比,var 不一定 会自动填入空格来使长度一致,取决于数据库系统
两个char则会自动添加空格使长度一致

基本模式定义

image.png
image.png
完整性约束
image.png

查询的基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
单关系查询
select dept_name from instructor where name = 'jack'

多关系查询
select A1, A2 from r1, r2 where P;

自然连接
course(cid,title,deptname,credits); insturctor+teacher(id name deptname salary cid sid)
select name,course_id
from insturctor natural join teaches;

from(instructor natural join teaches) join course using(course_id)//指定哪些相等列作为拼接
(如果不指定,可能有跨系授课的元组被删除,因为join的时候有两个相同属性列,都作为join的依据)

image.png

实际过程中,查询会尽可能只产生满足where子句谓词的笛卡尔积元素来优化执行

附加的基本运算

更名运算

1
2
3
4

select name as instructor_name ,course_id
from instructor as T, teaches
where instructor.ID = teaches.ID

字符串运算

image.png
eg: where building like ‘%Watson%’ /全文包含W-word就可以筛选出来

转义字符 escape‘’
eg:image.png

select子句的属性说明

select xx.* 所有的属性

排列元组的显示次序

order by、desc降序、asc升序
image.png

where子句谓词

image.png

集合运算

空值

嵌套子查询

数据库修改

sqlzoo总结

image.png

CASE

替换某个值为某个值
简单case:
CASE WHEN X THEN Y
else ‘其他’end,
把x换为Y,其他的不管
eg:select u.id,u.name,
2 (case u.sex
3 when 1 then ‘男’
4 when 2 then ‘女’
5 else ‘空的’
6 end
7 )性别
8 from users u;

将case命名为 性别

其他用法
将sum和case结合,分段统计
eg:image.png
在这里case when是作为搜索函数使用。

Group by

GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组

image.png

eg:
image.png

SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer

image.png

SELECT Customer,SUM(OrderPrice) FROM Orders
image.png

解释:groupby通过customer给price先分组,再处理sum聚集函数。

HAVING

在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用。(需要有一个能操作聚集函数的语句)
image.png
eg:
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000

image.png

between and

包括首尾的区间
image.png

order by 有个顺序,补全笔记的时候写上。


本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!