sql总结

来源:互联网 发布:中国人口有多夸张 知乎 编辑:程序博客网 时间:2024/05/16 10:57
 创建数据库
create database 数据库名 go

打开数据库
use 数据库名 go

创建数剧表
create table 表名(列名  类型  约束 )// primary key(主键),references(外键约束), identity(1.1)自增1  
,not null(不为空),check(*>2 and *<5)(check约束)

项数据表添加记录(一行数据)
insert 表名(列名) values(值)


项数据表添加记录(多行数据)
insert into 表名
select ‘值’,‘值’‘’,‘’ union
select '','',''union
select '','','' go


修改
update 表名 set 更改数据 where 条件 go(如 name=‘小龙女’)

删除
delete from 改数据 where 条件 go

查询
select 列名 from 表名 go

条件查询
select * from 改数据 where 条件 go

 降序查询
select * from 表名 order by 列名 desc

查询5条记录
select TOP 5 * form 表名 order by 列名 desc,列名

查询前20%行的记录
select TOP 20 PERCENT *from 表名 oreder by 列名


模糊查询
select * from 表名 where 列名 like '字段%'  (% 通配符)

select * from 表名 where 表名 like 'a_b'  (_匹配一个字符)

select * from 表名 where 列名 Like 'a[]'  ([]字符集合通配符)

select * from 表名 where 列名 IN('字符')   (IN()内的值是否存在)

select * from 表名 wherer 列名=‘值’ OR 列名=‘值’ (和IN的用处一样)

select * from 表名 where 列名 BETWEEN 200 AND 500  (between...and 两个值之间的数据)


聚合函数
select  sum(列名)  from 表名 (SUM(和),MAX(最大值),MIN(最小值),AVG(平均值),COUNT(某列的行数))

分组查询和联合查询
select 列名 ,列名,列名 from 表名 GROUP BY 列名,列名 ORDER BY  COUNT(列名),AVG(列名)  (GROUP  BY 分组)

对分组进行过滤
select 列名 列名 from 表名 GROUP BY 列名 HAVING 列名 ORDER BY 列名 (HAVING 分组后进行过滤)


联合查询
1.交叉查询
select * from 表名1 CROSS JOIN 表名2
2.内连接
select * from 表名1 JOIN 表名2 ON  表名1.列=表名2.列

select 列1 ,列2 form 表1 JOIN 表2  ON  表名1.列=表名2.列

外连接
1.左连
select 列1 ,列2, from 表1 LEFT JOIN 表2 ON 表名1.列=表名2.列 ORDER BY 列


2。右连
RIGHT JOIN

4。全连
FULL JOIN

5.自连
select 列 列 from 表1 JOIN 表1 ON 表名1.列=表名1.列
0 0
原创粉丝点击