sql增删查改语句+代码示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36027342/article/details/83054235

先上干货,如果不太清楚的话,可以看最后的代码示例yoyoyo!

1. 插入数据

1) 插入一行

insert[into]表名[(列名)]values(值列表)

(不能只插入半行或者几列数据,但允许为空|默认值;数据值要和列一一对应;字符类型,日期用’’;insert语句不能为标识列指定值(自增)

2) 一次插入多行数据

①insert select 向表中添加数据

 insert into addstudent[列名] select[对应列名] from student

注:addstudent是之前就建好的表

②select into 将现有表中数据添加到新表中

  select [列名] into 新表名 from 旧表名

注:新表名不能预先创建

拓展:复制表1结构到表2:select * into 表2 from 表1 where 1=0;复制表1到表2:select * into 表2 from 表1 where 1=1

③通过union 合并数据进行插入

insert 表名[列名] select 值 union

④通过逗号(,),values后面的多个值之间用逗号隔开

2. 更新数据

update 表名 set 列名=更新值[where]

注:运行结果,有可能更新一行数据,也有可能更新多行数据,但也有可能一行也不更新

3. 删除数据

delete [from] 表名 [where] (不会重新编号)
truncate table 表名 (会重新编号)
注:truncate比 delete执行速度快,但是truncate不能用于有外键约束的表
drop table 表名

4. 查询

select查询

①查询所有的数据列和行(*)

②查询部分行和列(指定)

③在查询中使用别名(as/=),或者空格直接写别名

④查询中常量列

⑤查询空值:is null,is not null

⑥查询返回限制的行数(top/percent)

⑦模糊查询 like (_ % [] [~])

⑧去重复(distinct)

排序order by (desc/ asc), 多列排序查询使用逗号分隔

分组查询:group by 多列分组查询使用逗号分隔
== 注:使用group by时,在select列表中是被分组的列或聚合==
函数组筛选:having 对分组后的条件的筛选必须用having

注:having和where可以在同一个select中使用,where子句中不能直接使用聚合函数

筛选顺序:where—group by —having

多表连接查询

笛卡儿积:select student.,SC. from Student,SC
等值连接:select student.,SC. from Student,SC where Student.Sno=Sc.Sno
自然连接: select student.*,Cno,Grade from Student,SC where Student.Sno=Sc.Sno
内连接查询:

①where

②inner join…on

select s.stuname,r.subject

from student
as s [inner] join result as r

on (s.stuno=r.stuno)

外连接查询:

①左外连接

left outer join…on

②右外连接

Right outer join…on

使用函数

  1. 日期函数(getdate,dateadd,datediff,datename,datepart)

注:datename返回的是字符串形式 datepart返回的是整数形式

  1. 数学函数(rand abs ceiling floor power round sign sqrt)

注:sign是判断正负数,有三个值,0,-1,1,

  1. 系统函数(convert current-user datalength host-name
    system-user user-name)

注:select datalength(6)—>4 select len(6)—>1

  1. 字符串函数(charindex,
    len ,upper ,ltrim, rtrim ,right ,replace
    ,stuff)

  2. 聚合函数:sum() avg() max() min() count()

sql_select

猜你喜欢

转载自blog.csdn.net/weixin_36027342/article/details/83054235