SQL Server(三)

一、数据库操作

create database 数据库名称 ——创建
drop database 数据库名称 ——删除
use 数据库名称 ——使用
go 两条SQL语句之间分隔

二、表的操作

create table 表名( 列名 类型 其它,列名 id类型 其它 ) ——使用
primary key ——主键
identity——自增长列
not null ——非空
unique ——唯一
references ——外键      

references 主表名(主表主键列)——设置外键格式

drop table 表名 ——删除

三、数据操作

1、增加数据(关键字:insert)

insert into 表名 values(每一列的值)
insert into 表名(列名) values(值)——给特定列添加值

2、删除数据(关键字:delete)

delete from 表名 where 筛选条件

3、修改数据(关键字:update)

update 表名 set 列名=值,列名=值 where 筛选条件

4、查询数据(关键字:select)

(1)简单查询

select * from 表名

select 列名 from 表名

select 列名 as 别名 from 表名

(2)条件查询 (where  or  and)

select * from 表名 where 条件1

select * from 表名 where 条件1 or 条件2

select * from 表名 where 条件1 and 条件2

(3)范围查询 (between  and)

select * from 表名 where 列名 between 值1 and 值2

(4)离散查询 (in  not in)

select * from 表名 where 列名 in(数据列表)

select * from 表名 where 列名 not in(数据列表)

(5)模糊查询  (like   %任意多个字符    _任意一个字符)

select * from 表名 where 列名 like ‘%_’

(6)排序查询 ( order by    desc降序   asc升序)

select * from 表名 order by 列名 ——默认升序,也可在列名后面加asc

select * from 表名 order by 列名 desc

(7)分组查询  (group by     having)

select * from 表名 group by 列名 having  条件 ——having需要跟在group by 后使用

(8)分页查询  (top  n 取前n个值)

select  top n * from 表名

(9)去重查询  (关键字: distinct )

select distinct 列名 from 表名

(10)聚合函数(统计函数)

select count(*) from 表名

select sum(列名) from 表名

select avg(列名) from 表名

select max(列名) from 表名

高级查询:

1.连接查询(关键字:join on)扩展列

select * from Info,Nation --形成笛卡尔积

select * from Info,Nation where Info.Nation = Nation.Code

select Info.Code,Info.Name,Sex,Nation.Name,Birthday from Info,Nation where Info.Nation = Nation.Code

select * from Info join Nation on Info.Nation = Nation.Code --join on 的形式

2.联合查询 (关键字:union)扩展行,一般不用

select Code,Name from Info

union

select Code,Name from Nation

3.子查询

一条SQL语句中包含两个查询,其中一个是父查询(外层查询),另一个是子查询(里层查询),子查询查询的结果作为父查询的条件。

--查询民族为汉族的所有人员信息 select * from Info where Nation = (select Code from Nation where Name = '汉族')

(1)无关子查询

子查询可以单独执行,子查询和父查询没有一定的关系

--查询系列是宝马5系的所有汽车信息 select * from Car where Brand =(select Brand_Code from Brand where Brand_Name = '宝马5系')

(2)相关子查询

--查找油耗低于该系列平均油耗的汽车

select * from Car where Oil<(该系列的平均油耗) select avg(Oil) from Car where Brand = (该系列)

select * from Car a where Oil<(select avg(Oil) from Car b where b.Brand = a.Brand)

select min(列名) from 表名

原文地址:https://www.cnblogs.com/asdyzh/p/9756280.html