SQL语句记录
- 截取字符串函数:
substring(字符串,位置,截取长度);
- 统计不重复的数据总数:会忽略列值为NIULL的行
count(distinct 字段名) as 别名
- 统计表总条目数:不会忽略列值为NIULL的行
count (*) as 别名
- 统计商品订单总价格:
sum (商品数量的字段名*商品单价的字段名) as total_money
- 将查询的结果保存到结果表:
insert into 要保存到的表名
select
字段名
form 要查询的表名
where 条件
group by 条件;
- 字段的值分组改别名:
case when 字段名 = 某值 then '别名'
when 字段名 = 某值 then '别名'
else '其他'
end as '别名',
- 开窗排序函数:
- rank() #1224447 模式
select
*,
rank() over (order by 某表.字段名 desc) as 别名
from
(xxx
xxxx) as 某表 ;
- dese_rank() #12233334模式
select
dese_rank() over (partition by 分组字段 order by 排序字段 desc) as 别名
- row_number() #123456模式
select
row_number() over (partition by 分组字段 order by 排序字段 desc) as 别名
- 自分类: #只有一张表,把它当作多张表用
select
*
from product_cat t3,product_cat t2,product_cat t1
where t3.pid=t2.catld and t2.pid=t1.catld
9.将查询出来的临时表直接创建成新表:
create table 新表名
as
select
xxx
xxx
xxx
from
xxx
xxx
xxx
where xxx
优点:不用提前建表,缺点:不会自动创建主键
10.左外关联:
作用:将左表的数据全部输出,右表有对应数据则输出,没有对应数据则补NULL
from
表1 as a
left join
表2 as b on 相连条件
left join
表3 as c on 相连条件
where xxx
11.添加索引 (sql调优)添加到条件判断相连的字段
- 唯一索引
create unique index 索引名 on 表名(字段名);
- 普通索引
create index 索引名 on 表名(字段名);
12.插入表语句:
insert into 要插入的表名
select
....
- 插入本表一些数据
insert into 表名(字段名) values(字段名对应的值);
13.函数
- 取当前日期:
curdate();
- 转换成大写
upper()
- 转换成小写
lower();
- 返回字符串的长度
length()
- 提取近似音函数:用来近似比较
soundex()
- 取绝对值函数
abs()
- 合并字段函数:
concat()
- 求平均值函数: 函数会忽略列值为NULL的行
avg()
avg(distinct 字段名)
14.过滤 having:
where在数据分组前进行过滤,having在数据分组后进行过滤;
15.in与子句查询一起使用
where xxx in (子句)
16.创建组合查询(union):
xxxx
...
union
xxxx
...
order by
注意:order by 只能出现一次且只能出现在最后
17.进行表的复制(select into)sql server 专属
select*into 要创建的表名 from 表名;
18.更新表中的特定行
update 表名
set 字段名=值
where 条件锁定(某行)
- 更新表中的全部行
update 表名
set 字段名=值
- 删除某表的某个值优势:可删除整列
update 表名
set 字段名=null
where 条件锁定(某行)
19.删除某行(delete)
delete from 表名
where 条件锁定某行
如果没有指定where将删除表中的全部行,谨慎使用delete语句
- 删除整个表 优点:速度比用delete更快,因为其不用记录数据的变动
truncate 表名
20.指定默认值
create table 表名
(
字段名 数据类型 default 1
) #默认值为1
21.更改表的定义
- 增加列
alter table 表名
add 要增加的列名 数据类型
- 删除列 并非对所有的DBMS有效,且该列包含数据的时候可能无法修改
alter table 表名
drop column 列名
- 不能更改已有列的类型
22.删除表
drop table 表名;
- 重命名表
rename table 旧表名 新表名 #未验证该语句的正确性
23.视图
相当于封装了一个查询语句的脚本,其根本不含数据,而且视图中不能使用order by 对数据进行排序
create view 视图名 as
select
...
- 删除视图
drop view 视图名;
24.添加约束
alter table 表名
add constraint 约束类型(要约束的字段名);