在这儿下载sql脚本,快速建立数据库,这样可以很方便的试验select语句了。http://download.csdn.net/detail/u011405813/6356489
我用的是Postgres,老师说这个数据库比较符合标准。
选择出所有计算机学院的教师名字和课程名:
select name,title from instructor,teaches,course where instructor.ID=teaches.ID and instructor.dept_name='Comp. Sci.' and course.course_id=teaches.course_id;
有一种更简单的查询方式,使用自然连接:
select name,title from instructor natural join teaches natural join course where instructor.dept_name='Comp. Sci.';
自然连接只考虑那些在两个模式中相同属性取值相等的元祖,这样看起来效率会更高。但其实效率是差不多的,因为数据库会自己优化,不过这种写法显然要简单一点。。
有时候使用自然连接时,有多个属性相同,而我们只需要其中的一个相同属性取值相等,这时候就可以使用自然连接的构造形式了。
比如,我想找出所有的老师名称以及他们对应的课程名,而不用管他们的dept_name属性是否相同:
select name,title from (instructor natural join teaches) join course using (course_id);
这样,自然连接的时候就会考虑course_id相同的元祖了,不管dept_name是否相同。(这里有点牵强。。)
更名运算,as,既可以重命名属性,也可以重命名关系:
select name as instructor_name ,course_id from instructor ,teaches where teaches.ID=instructor.ID;
select T.name ,S.course_id from instructor as T ,teaches as S where T.ID=S.ID;
重命名还有另外一个作用,比如我们想找出满足下列条件的所有老师的姓名,他们的工资至少比Biology系某一个教师的工资要高。
select distinct T.name from instructor as T,instructor as S where T.salary > S.salary and S.dept_name='Biology';
注意我们不能写成,instructor.salary这样的写法,因为这样并不清楚到底是希望引用哪一个instructor.
在上述查询中,T和S可以被认为是instructor关系的两个拷贝。T和S通常被称为相关变量。
SQL在字符串上有很多函数,例如串联,使用||,用upper将字符串S转化为大写,或者用lowwer()将字符串转化为小写。去掉字符串后面的空格使用trim()等。
比如,使用
select distinct upper(T.name) from instructor as T,instructor as S where T.salary > S.salary and S.dept_name='Biology';
将所有符合条件的名字转化为大写后输出。
SQL一般使用%来匹配任意字符串,使用_匹配一个字符。
我们可以使用
select dept_name from department where building like '%Watson%';
来查询出名字中有Watson的所有建筑物的名称。
SQL使用escape关键词来指定转义字符,比如我们可以使用
like 'ab\%ab%' escape '\' 来查找含有子串'ab%cd'的字符串
SQL还允许使用not like 比较运算符来搜寻不匹配项。
select name from instructor where name not like 'E%';
可以找出名字不是以E开头的老师.
集合运算
找出在2009年秋季开课或者2010年春季开课的所有课程。
(select course_id from section where semester='Fail' and year = 2009)union(select course_id from section where semester='Spring' and year=2010);
与Select子句不同,union子句会将结果自动去重.
如果不想去重,可以使用union all
(select course_id from section where semester='Fail' and year = 2009)union all(select course_id from section where semester='Spring' and year=2010);
找出2009年秋季和2010年春季都开的课程。
(select course_id from section where semester='Fall' and year = 2009)intersect (select course_id from section where semester='Spring' and year=2010);
找出在2009年秋季开但是不在2010年春季开的课程。
(select course_id from section where semester='Fall' and year = 2009)except all(select course_id from section where semester='Spring' and year=2010);