【3-10】数据库语句编写

一、关于数据库语句

(1)创建数据库         create database 数据库名

注:数据库名不能以中文、数字、符号开头

例:create datdbase student

(2)删除数据库        drop database 数据库名

例:drop database student

(3)使用数据库   use 数据库名

例:use student

二、数据库中表的语句

(1)创建表    create   table  表名

列名  数据类型

.......

例:

【3-10】数据库语句编写

 (2)删除表    drop table 表名

例:drop table student

 (3)修改表:

1》添加列:alter table表名 add 列名 数据类型 default 默认值 是否为空(null/not null)

例:alter table student add class nvarchar(50)

2》删除列:alter table 表名 drop column 列名

例:alter table student drop column class

3》修改列 alter table 表名  Modify (列名  数据类型  default 默认值 是否为空)--常用于修改列的数据类型

eg:alter table student Modify class nvarchar(100);

(4)表中约束条件的添加

1、主键约束:1》在被约束列后加 primary key

2》添加主键:alter table 表名 add constrain 主键名 primary key (表名.某一符合列)

2、唯一约束:1》在被约束列后加 unique--类似于添加唯一不重复字段为索引

2》CREATE UNIQUE(省略此字段为索引添加方法) INDEX 索引名 ON 表名(列名)

3、外键约束:alter table 外键表名 add constraint 约束名称 foreign key(外键字段) references 主键表名(约束列名)

4、自增:identity(开始数,自增数)

5、不能为空:not null

三、列中数据的语句

(1)添加数据   insert into 表名 values('字符串','时间日期','true/false',值)

例:insert into student values('s001','张三','true','2011-09-01',98.05)

(2)修改数据  update 表名 set 列名=值

例:update student set sex='false'

(3)删除数据   delete  from 表名/truncate table 表名

注:delete逐行删除,truncate全部清空删除

例:delete from student

truncate table student

(4)查询数据   select *from 表名

例:select*from student

四、条件操作语句

(1)条件修改: update 表名set 列名=值 where 列名=值

例:update student set score=98 where name='张三'

(2)条件删除: 

 delete from 表名where 列名=值

(3)高级查询

1、条件查询:select 列名1,列名2 from 表名where 列名=(<,>,<=,>=)值and/or 列名...

2、模糊查询:select*from 表名where列名like'%值%'

3、排序查询:select*from表名where order by 列名asc(升序)/desc(降序)

4、去重查询:select distinct 列名from表名

5、分组查询:select 某一列名from 表名 group by 对应的列名