一、数据库操做sql
create database student_info -- 建立数据库 drop database student_info -- 删除数据库
二、表操做数据库
-- 建立表 create table student( id int not null primary key, name varchar(20) not null, age int null, sex varchar(10) ) -- 删除表 drop table student -- 修改表,增长一个列 Alter table student add column address varchar(50)
三、sql语句函数
简单语句
spa
插入(增):insert into student(id, name, address) values(1, 'Xiaohong', 16) 删除(删):delete from student where age<=6 更新(改):update student set name='Lily' where id=1 查询(查):select * from student
高级语法code
模糊查询:select * from student where name like '%Xiao%' 排序:select * from student order by field1,field2 desc 总数:select count(*) as totalcount from student 函数:select sum(age) as sumAge, avg(age) as avgAge, max(age) as maxAge, min(age) as minAge from student 前几: select top 10 * from student order by age desc 去重: select distinct name from student 多个条件: select * from student where name like '%Xiao%' and age=16 or age=20 between: select * from student where age between 10 and 20 in: select * from student where name in ('Lily', 'Amy') 分组: select age, count(*) from student group by age 分组带条件: select age, count(*) from student group by age where age >10 having count(*)<5
四、表链接blog
JOIN: 若是表中有至少一个匹配,则返回行
LEFT JOIN: 即便右表中没有匹配,也从左表返回全部的行
RIGHT JOIN: 即便左表中没有匹配,也从右表返回全部的行
FULL JOIN: 只要其中一个表中存在匹配,就返回行排序
create table course( cno int not null primary key, cname varchar(20) not null ) create table StudentCourse( sno int not null, cno int not null, score double ) -- 表链接, 查找全部学生的选课记录 select s.name as 学生姓名,sc.cno as 选修课号,sc.score as 成绩 from student s, StudentCourse sc where s.id=sc.sno -- 内链接, 查找全部成绩及格的选课记录 select s.name as 学生姓名,sc.cno as 选修课号,sc.score as 成绩 from student s inner join StudentCourse sc on s.id=sc.sno where sc.score>60 -- 左链接, 查找全部学生的选课记录 select s.id as 学号,sc.cno as 选修课号,sc.score as 成绩 from student s left join StudentCourse sc on s.id=sc.sno -- 嵌套查询, 查找王敏同窗的选课记录 select * from StudentCourse where sno in ( select id from student where name='王敏' ) --查找每一个学生大于自身平均分的科目 select cno from StudentCourse a where score> ( select avg(score) from StudentCourse b where a.sno=b.sno )
五、SQL 约束索引
约束用于限制加入表的数据的类型。能够在建立表时或表建立后规定约束。约束主要有如下几类:table
create table student( id int not null, name varchar(20) not null, age int null DEFAULT 1, UNIQUE (name), PRIMARY KEY (id), CONSTRAINT chk_age check (age>0 AND age<200), CONSTRAINT uq_name unique(name) )
六、索引class
您能够在表中建立索引,以便更加快速高效地查询数据。
-- 建立索引 create index idx_age on student(age asc) create unique index idx_name on student(name) -- 删除索引 drop index idx_name
七、视图
视图是基于 SQL 语句的结果集的可视化的表。
-- 删除视图 if exists (select * from dbo.sysobjects where id = object_id(N'dbo.young_student') and objectproperty(id, N'isview') = 1) drop view young_student -- 建立视图 create view young_student as select * from student where age<10