当前位置: 数据库>sqlserver
Sql 语句学习指南第1/2页
来源: 互联网 发布时间:2014-09-05
本文导语: 1.在查询结果中显示列名: a.用as关键字:select name as '姓名' from students order by age b.直接表示:select name '姓名' from students order by age 2.精确查找: a.用in限定范围:select * from students where native in ('湖南', '四川') ...
1.在查询结果中显示列名:
a.用as关键字:select name as '姓名' from students order by age
b.直接表示:select name '姓名' from students order by age
2.精确查找:
a.用in限定范围:select * from students where native in ('湖南', '四川')
b.between...and:select * from students where age between 20 and 30
c.“=”:select * from students where name = '李山'
d.like:select * from students where name like '李%' (注意查询条件中有“%”,则说明是部分匹配,而且还有先后信息在里面,即查找以“李”开头的匹配项。所以若查询有“李”的所有对象,应该命令:'%李%';若是第二个字为李,则应为'_李%'或'_李'或'_李_'。)
e.[]匹配检查符:select * from courses where cno like '[AC]%' (表示或的关系,与"in(...)"类似,而且"[]"可以表示范围,如:select * from courses where cno like '[A-C]%')
3.对于时间类型变量的处理
a.smalldatetime:直接按照字符串处理的方式进行处理,例如:
select * from students where birth > = '1980-1-1' and birth 85
order by 3
10.其他
a.对于有空格的识别名称,应该用"[]"括住。
b.对于某列中没有数据的特定查询可以用null判断,如select sno,courseno from grades where mark IS NULL
c.注意区分在嵌套查询中使用的any与all的区别,any相当于逻辑运算“||”而all则相当于逻辑运算“&&”
d.注意在做否定意义的查询是小心进入陷阱:
如,没有选修‘B2'课程的学生 :
select students.*
from students, grades
where students.sno=grades.sno
AND grades.cno 'B2'
上面的查询方式是错误的,正确方式见下方:
select * from students
where not exists (select * from grades
where grades.sno=students.sno AND cno='B2')
11.关于有难度多重嵌套查询的解决思想:
如,选修了全部课程的学生:
select *
from students
where not exists ( select *
from courses
where NOT EXISTS
(select *
from grades
where sno=students.sno
AND cno=courses.cno))
a.用as关键字:select name as '姓名' from students order by age
b.直接表示:select name '姓名' from students order by age
2.精确查找:
a.用in限定范围:select * from students where native in ('湖南', '四川')
b.between...and:select * from students where age between 20 and 30
c.“=”:select * from students where name = '李山'
d.like:select * from students where name like '李%' (注意查询条件中有“%”,则说明是部分匹配,而且还有先后信息在里面,即查找以“李”开头的匹配项。所以若查询有“李”的所有对象,应该命令:'%李%';若是第二个字为李,则应为'_李%'或'_李'或'_李_'。)
e.[]匹配检查符:select * from courses where cno like '[AC]%' (表示或的关系,与"in(...)"类似,而且"[]"可以表示范围,如:select * from courses where cno like '[A-C]%')
3.对于时间类型变量的处理
a.smalldatetime:直接按照字符串处理的方式进行处理,例如:
select * from students where birth > = '1980-1-1' and birth 85
order by 3
10.其他
a.对于有空格的识别名称,应该用"[]"括住。
b.对于某列中没有数据的特定查询可以用null判断,如select sno,courseno from grades where mark IS NULL
c.注意区分在嵌套查询中使用的any与all的区别,any相当于逻辑运算“||”而all则相当于逻辑运算“&&”
d.注意在做否定意义的查询是小心进入陷阱:
如,没有选修‘B2'课程的学生 :
select students.*
from students, grades
where students.sno=grades.sno
AND grades.cno 'B2'
上面的查询方式是错误的,正确方式见下方:
select * from students
where not exists (select * from grades
where grades.sno=students.sno AND cno='B2')
11.关于有难度多重嵌套查询的解决思想:
如,选修了全部课程的学生:
select *
from students
where not exists ( select *
from courses
where NOT EXISTS
(select *
from grades
where sno=students.sno
AND cno=courses.cno))