数据操作:增 删 改 查
1、创建数据库
create database 库名
go
use 库名
go
2、创建表
create table 表名
(
列名 类型,
列名 类型,
列名 类型
)
例子:
create table one
(
daihao varchar(10),
shuming varchar(50),
zuozhe varchar(10),
chubanshe varchar(50),
shijian datetime
)
3、添加行记录
insert into 表名(列名,列名,列名)
values('值','值','值')
例子:
insert into one(daihao,shuming,zuozhe,chubanshe,shijian)
values('b001','计算机基础教程','苗英成','淄博汉启出版社','2015-5-31')
注意:
列名不加引号 值名必须加引号 列名和值要一一对应
插入列的时候可以删除列或者随意插列 但要一一对应 并且删的和插入的必须是上面所建的表里的
4.修改
update 表名 set 列名 ='表达' where 条件表达式
例子:update one set zuozhe ='韩雪' where zuozhe='魏雪漫'
5.删除
delete from 表名 where '条件表达式'
例子:delete from one where daihao='b001'
(一)对列的操作叫做投影
1、查询所有的列 select * from 表名
例子:select *from Car --查询Car表中所有的数据
2、查询某两个列或者多个列 select 列名,列名,列名… from 表名
例子:select Name ,Price from car --查询car表中名字,价格
3、计算列 如何查表中没有的列 select name ,price*numbers chengben from fruit 这样会显示两列 列的名称为name 和 chenben
修改列名 name后面用空格就,然后写上名称 select name 名称,price 价格 from fruit
(二)对行的操作叫做筛选(等值 不等值 多条件)
1、等值
select * from Car where Brand = 'b003'
2、不等值
select * from Car where Price >50
select * from Car where Price <30
3、多条件 用 and 或者 or 还有 between and
select *from Car where Price >30 and Price <50
select *from Car where Price>30 and Oil<5
select * from Car where Price>50 or Price <20
--between and 是大于等于 小于等于
select *from Car where price between 30 and 50
4、消除重复的行 用distinct
select distinct oil from Car 查油耗这一行并且把相同的去掉(看看油耗有多少种,相同的会去掉)
搞清楚根据价格找排量
select distinct exhaust from car where price>40 and price <50 看看价格在40-50之间的排量有多少
4、模糊查询用like 和 %
示例:
select * from Car where Name like '奥迪%' 表示 name 的前两个字是奥迪 后面的任意多
select * from Car where Name like '%型' 表示 name 的最后一个字是型 前面的任意多
select * from Car where Name like '%5%' 表示 name 的中间有个5 前后任意多
select * from Car where Name like '__5%' 表示 name 的第三个字是5 前面只有两个字符后面任意多
5、修改行中的多个列 操作
update fruit set numbers = numbers-20 where name ='桔子'
update fruit set numbers = 30 where name = '苹果'
update fruit set price = 5.20,numbers=50,source='肥城' where name='桃子'
(其他)
控制条的方法 一页显示几条用的是top
select top 条数 * from 表名
select top 10 * from car
升序排列
select * from 表名 order by 列名(按照这个列名来升序排列)
select * from car order by price (或者后面写asc 不写默认是升序)
降序排列
select * from 表名 order by 列名 desc
select * from car order by price desc
order by 后面是主排序列 逗号后面是次排序列
select * from car order by oil , price desc (先按照oil的升序排列,对oil中相同的再按照price的降序来排列)