SQL中的常见问题

1.with as 的用法

with table_name as (查询语句)
select * from table_name

解释:意思就是将查询语句放入到临时表table_name中去,然后再进行对临时表table_name的操作。
如果想要多个临时表,后面可以继续跟as语句,例如:

with 
table1 as (查询语句1),
table2 as (查询语句2),
table3 as (查询语句3)
select * from ....

三个临时表创建完毕后再写对该三个表操作的语句。

2.存储过程

(1)创建存储过程

create proc pro_name
as
SQL_statements

例如:

create proc proc1
as
select * from table1

(2)创建带参数的存储过程

create proc pro_name(@startId int, @endId int) 
as 
select * from student where id between @startId and @endId`

(3)调用存储过程
exec proc1

(4)修改存储过程

alter proc proc_name 
as 
SQL_statements

3.几个删除的比较

SQL里删除操作有三个函数可用:Drop,Truncate,Delete,具体区别如下:
相关函数|删除数据 | 删除定义(结构)| 释放空间
---|---|---|---
Delete |是 |否 |否
Truncate |是 |否 |是
Drop |是 |是 |是

删除的速度,一般来说: drop>truncate >delete

4.SQL性能优化

(1)where子句的顺序
SQL Sever和ORACLE是采用自下而上解析where子句的,也就是说where里的子句是从后往前执行的,所以,要把那些能够过滤掉最大数量记录的子句写在最后。
(2)on、where和having这三个都可以加条件的句子,on先执行,where次之,having最后。在多表连接查询中,先通过on子句过滤掉不符合条件的记录,把多个表合成临时表后,再由where条件进行过滤,再进行计算,计算完成后再由having条件进行过滤。
(3)使用索引
在数据量大时可以使用索引,来提高查询效率。但是索引也会付出相应代价,就是索引需要空间来存储,也需要定期维护。在数据增删改时,相应的索引也要发生变化,降低了增删改的效率。
(4)用>=代替>
比如:select * from table where id >=4 语句,DBMS直接跳到id=4的记录,而如果使用select * from table where id >3 语句,DBMS先定位到id=3的记录,然后再向前扫描到第一个id>3的记录。
(5)用in来代替or
比如下面两句sql,第二句比第一句效率高
1.select * from table where id = 2 or id = 3 or id = 4
2.select * from table where id in (2,3,4)
(6)优化group by子句
下面两种语句执行效果一样,但明显第二种语句效率更高。
1.select job,avg(sal) from table group by job having job = "job1" or job = "job2"
2.select job,avg(sal) from table where job = "job1" or job = "job2" group by job
(7)使用表的别名
在多表连接查询时,使用表的别名可以减少解析的时间,并且也可以避免由于列名引起的语法错误。

5.case when的用法

case when 有两种格式写法
(1)简单case函数

case sex
when '1' then '男'
when '2' then '女'
else '其他'
end

(2)case搜索函数

case when sex = '1' then '男'
when sex = '2' then '女'
else '其他'
end

需要注意到的是,case when 函数只返回第一个符合条件的值,其后所有的都将会被忽略。

举例:暂略

6.union的用法

union是对字段类型以及个数一样的两个表进行行连接,直接对两个select语句中间加union即可,举例

select * from table1 where ...
union
select * from table2 where ...

如果要对合并后的表进行排序的话,只在最后加上order by子句即可,union函数不支持对某一个表格排序,要么整体排序,要嘛不排序。order by子句写在最后就是对合并后的表格排序。如下所示:

select * from table1 where ...
union
select * from table2 where ...
order by ...

如果两个表格里有重复的行,union 函数会去重,如果不要求去重,可用union all函数。

猜你喜欢

转载自www.cnblogs.com/xiaoma927/p/9895381.html
今日推荐