select (all|distinct) <目标列表达式> [别名][,<目标列表达式> [别名]]...
from <表名或视图名> [别名][,<表名或视图名> [别名]]...|(<select语句>) [as] <别名>
[where <条件表达式>]
[group by <列名1> [having <条件表达式>]]
[order by <列名2> [asc|desc]]
[limit <行数1> [offset <行数2>]];
下面以”学生选课“数据库为例,说明select语句的各种用法
select sno,sname from student;
select * from student;
///等价于
select sno,sname,ssex,sbirthdate,smajor from student;
select sname,(extract(year from current_date)-extract(year from sbirthdate)) '年龄'
from student;
'年龄’是通过指定别名来改变查询结果的列标题
extract(year from current_date)是kingbase提供的内置函数,不同DBMS提供的内置函数不同,所以在写sql语句时一定要参考所使用的产品手册
可以在select语句中加上说明含义的一个列标题:
select sname,'date of birth:',sbirthdate,smajor
from student;
两个本来并不完全相同的元组在投影到指定的某些列上后,可能会变成相同的行。可以用distinct消除它们:
select sno from sc;
//等价于
select all sno from sc;
select distinct sno from sc;
查询条件 | 谓词 |
---|---|
比较 | =, >, <, >=, <=, !=, <>, !>, !<; not+上述运算符 |
确定范围 | between and, not between and |
确定集合 | in, not in |
字符匹配 | like, not like |
空值 | is null, is not null |
多重条件(逻辑运算) | and, or, not |
比较大小:
select sname from student
where smajor='计算机科学与技术';
select sname,ssex from student
where extract(year from sbirthdate) >= 2000;
select distinct sno from sc
where grade < 60;
这里使用了distinct短语,当一个学生有多么课程不及格时,其学号也只列一次
确定范围:
select sname,sbirthdate,smajor from student
where extract(year from current_date) - extract(year from sbirthdate)
between 20 and 23;
select sname,sbirthdate,smajor from student
where extract(year from current_date) - extract(year from sbirthdate)
not between 20 and 23;
确定集合:
select sname,ssex from student
where smajor in ('计算机科学与技术','信息安全');
相反,不属于则是not in
select sname,ssex from student
where smajor not in ('计算机科学与技术','信息安全');
[not] like '匹配串' [escape '换码字符'];
即查找指定的属性列值与<匹配串>相匹配的元组
a.%代表任意长度的字符串。例如:a%b表示以a开头,b结尾的任意长度的字符串。如acb,addgb,ab等都满足该匹配串
b._代表任意单个字符。例如:"a_b"表示以a开头,以b结尾的长度为3的任意字符串,如acb, afb等都满足该匹配串
select * from student
where sno like '20180003';
//等价于
select * from student
where sno='20180003';
//如果like后面的匹配串种不含通配符,则可以用=代替like,用!=或者<>运算符代替not like谓词
select sname,sno,ssex from student
where sname like '刘%';
select sno,sname from student
where sno like '2018%'; //学号的数据类型是字符,用字符匹配
select cname,cno from course
where cno like '81__6'; //课程号为固定长度,占5个字符大小
select sname,sno,ssex from student
where not like '刘%';
如果用户要查询的字符串本身就含有通配符%或_,这时就要使用escape’<换码字符>'短语对通配符进行转义了。
select sno,credit from course
where cname like 'db\_design' escape '\';
”escape’'表示”\“为换码字符。这一匹配串中紧跟在”\“后面的字符”_“不再具有通配符的含义,转义为普通的 _ 字符“
select * from course
where cname like 'db\_%i__' escape '\';
//第一个_前有换码字符,所以被转义为普通的_字符。而i后的两个_的前面均没有换码字符,所以它们仍作为通配符
某些学生选修课程后没有参加考试,所以有选课记录但没有考试成绩。
select Sno,Cno
from sc
where grade is null;
//注意这里的“is”不能用“=”代替
select sno,cno
from sc
where grade is not null;
逻辑运算符and和or可用来连接多个查询条件。and的优先级>or,但用户可以用括号改变优先级
select sno,sname,ssex
from student
where smajor='计算机科学与技术专业' and extract(year from sbirthdate) >= 2000;
select sname,ssex
from student
where smajor = '计算机科学与技术' or smajor = '信息安全';