您的位置:首页 > 编程语言 > Java开发

Java_09_08课堂总结

2011-09-08 13:03 330 查看
数据库命令
一、基本查询

1、选择列-----select子句

select 列名1,列名2,。。。

from 表名

select 学号,姓名,性别,出生日期

from xs;

select * from xs;

给指定列起别名

select 列名 as 别名,列名 别名,...

from 表名

查询计算列

select 姓名,总学分,总学分*1.1 as 提高后的总学分

from xs

消除查询结果中的重复行

select distinct 列名

from 表名

替换查询结果中的数据

select 学号,姓名,

case

when 总学分<50 then '不及格'

when 总学分>=50 and 总学分<60 then '及格'

when 总学分>=60 then '优秀'

end

from xs;

使用聚合函数,通常和后面要将group by分组汇总的子句一起使用。

select max(总学分),min(总学分)

from xs;

max(数值型列) 求这一列的最大值

min(数值型列) 求这一列的最小值

avg(数值型列) 求这一列的平均值

sum(数值型列)求这一列的总和

count(*)求的是表格中的记录的行数

count(指定某一列) 求是指定列不为空的取值的个数(包括重复数据)

count(distinct 指定某一列) 指定列的取值去掉null值,去掉重复值后的记录的个数

2、选择运算------where子句:设定查询的条件。

(1)关系表达式

> >= < <= = <> !=

select *

from xs

where 总学分<>45;

select *

from xs

where 备注<=>null; 或 where 备注 is null;

注意:空值的比较

<=> 相等关系的比较

is null is not null

(2)逻辑表达式

select 学号,姓名,总学分

from xs

where 总学分>=40 and 总学分<=50;

select 学号,姓名,总学分

from xs

where 总学分<45 or 总学分>50;

and &&

or ||

not !

select 学号,姓名,总学分

from xs

where not (总学分>=40 and 总学分<=50)

select 学号,姓名,总学分

from xs

where !(学号='081101');

(3)between val1 and val2 :在[val1,val2] 连续的区间

select 学号,姓名,总学分

from xs

where 总学分 between 45 and 50;

select 姓名,出生时间

from xs

where 出生时间 not between '1989-1-1' and '1989-12-31';

select 姓名,出生时间

from xs

where 出生时间>='1989-1-1' and 出生时间<='1989-12-31';

(4)不连续的若干个取值:in (不连续的若干个取值)

select 姓名,总学分

from xs

where 总学分=38 or 总学分=40 or 总学分=48;

等价

select 姓名,总学分

from xs

where 总学分 in (38,40,48);

select 姓名,专业名,总学分

from xs

where 专业名='计算机' or 专业名='通讯工程';

select 姓名,专业名,总学分

from xs

where 专业名 in('计算机','通讯工程');

(5)模糊查询 like '模式匹配字符串'

在“模式匹配字符串”中可以:%任意个任意的字符 _一个任意的字符

select 学号,姓名,总学分

from xs

where 姓名 like '王%';

王林 王小小 王

select 学号,姓名,总学分

from xs

where 姓名 like '王_';

select 学号,姓名

from

xs

where 学号 like '__11__';

select *

from xs

where 姓名 like 'a%';

select *

from xs

where 姓名 like '%tf';

select 姓名,专业名

from xs

where 姓名 like '%#_%' escape '#';

正则表达式

rlike '正则表达式的字符串'

或者 REGEXP '正则表达式的字符串'

select 学号,姓名,专业名

from xs

where 姓名 rlike '^王';

select 学号,姓名,专业名

from xs

where 姓名 rlike '林$';

rlike '.*'

rlike '^08.*08$'

rlike 'a+'

rlike '[^a-z]'

3、order by 对查询结果进行排序

select 列名1,列名2,...

from 表名

where 查询条件

order by 列名1 [asc|desc][,列名2,...]

select 学号,姓名,出生时间

from xs

order by 出生时间 desc;

select 学号,课程号,成绩

from xs_kc

order by 课程号 desc,成绩 desc;

如果order by子句中排序列有多个,先按第一个指定列排序,在第一个指定列的值相同的情况下,再按第二个指定列的值进行排序。

如果排序列有多个,每一列都需指明是升序还是降序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: