简单查询:一、投影select * from 表名select 列1,列2... from 表名 select distinct 列名 from 表名 二、筛选 select top 数字 列|* from 表名 (一)等值与不等值 select * from 表名 where 列名=值 select * from 表名 where 列名!=值 select * from 表名 where 列名>值 select * from 表名 where 列名 <值 select * from 表名 where 列名> =值 select * from 表名 where 列名<=值 (二)多条件与范围 select * from 表名 where 条件1 and|or 条件2 ... select * from 表名 where between ... and ... select * from 表名 where 列 in (值列表) (三)模糊查询 like % _ select * from 表名 where 列 like '%_....' 三、排序 select * from 表名 where 条件 order by 列名 ASC|DESC,列名 ASC|DESC 四、分组: 统计函数(聚合函数) count(), max(), min(), sum(), avg() count()统计总行数 count(*)得到所有的行数 count(列)得到该列中所有非null个数。 select COUNT(*) from car where Brand='b003' max(列) 这一列的最大,min(列)这一列的最小 select min(price) from car sum(列)这一列的和,avg(列)这一列的平均 select AVG(price) from car group by ...having... 1.group by后面跟的是列名。 2.一旦使用group by分组了,则select和from中间就不能用*,只能包含两类东西一类是:group by 后面的列名,另一类是统计函数 select Oil,avg(price) from Car group by oil 对于统计函数生成的列,默认是无列名,可以通过下面的方法指定列名。 select Oil as 油耗,COUNT(*) as 数量,avg(price) 均价 from Car group by oil having后面一般跟得是统计函数。它用来对分组后的数据进一步筛选。 复杂查询: 一、连接查询 把多个表的列合在一个界面视图中。 思想:1.生成笛卡尔积。2.对笛卡尔积进行筛选。3.选择列进行显示。 select 表1.列1,表1.列2,表2.列1,表2.列2…… from 表1,表2 where 表1.列=表2.列 select * from 表1 join 表2 on 表1.列=表2.列 join 表3 on 表2.列=表3.列 左连(left join),右连(right join),全连(full join) 值>
二、联合查询把多个表的行合在一个界面视图中。用union把两个查询组合在一起。要求是这两个查询的列要一一对应。三、子查询(嵌套查询)(一)无关子查询:至少是两层查询,在外层查询的里面再写查询。里层查询为外层查询提供查询的中间内容。
create database testgouse testgocreate table student( --学号 sno varchar(3) not null primary key, --姓名 sname varchar(4) not null, --性别 ssex varchar(2) not null, --出生年月 sbirthday datetime, --所在班级 class varchar(5) ) go create table teacher ( --教工编号 tno varchar(3) not null primary key, --教工姓名 tname varchar(4) not null, --教工性别 tsex varchar(2) not null, --教工出生日期 tbirthday datetime, --职称 prof varchar(6), --所在部门 depart varchar(10) ) go create table course ( --课程号 cno varchar(5) not null primary key, --课程名称 cname varchar(10) not null, --教工编号 tno varchar(3) references teacher(tno) ) go create table score ( --学号 sno varchar(3) not null references student(sno), --课程号 cno varchar(5) not null references course(cno), --成绩 degree decimal(4,1) ) go insert into student values('108','曾华','男','1977-09-01','95033') insert into student values('105','匡明','男','1975-10-02','95031') insert into student values('107','王丽','女','1976-01-23','95033') insert into student values('101','李军','男','1976-02-20','95033') insert into student values('109','王芳','女','1975-02-10','95031') insert into student values('103','陆君','男','1974-06-03','95031') insert into teacher values('804','李诚','男','1958-12-02','副教授','计算机系') insert into teacher values('856','张旭','男','1969-03-12','讲师','电子工程系') insert into teacher values('825','王萍','女','1972-05-05','助教','计算机系') insert into teacher values('831','刘冰','女','1958-08-14','助教','电子工程系') insert into course values('3-105','计算机导论','825') insert into course values('3-245