SQL数据库select基本使用 |
您所在的位置:网站首页 › 数据库语句用法 › SQL数据库select基本使用 |
Select基本语句基本语法: select 列名 from 表名 【例】从学生表(Student)中查询所有学生的学号 单列 select 学号 from Student 【例】查询课程表课程号、课程名、学分 多列用逗号“,”分隔符 select 课程号,课程名, 学分 from Course 【例】查询学生表(Student)中的所有信息 所有列用’ * ’ 代替 select * from Student 当在select语句指定列的位置上使用*号时,表示选择表的所有列。 条件查询 【例】查询Student表中姓名为李明的相关信息 用where指明条件 select * from Student where 姓名='李明'【例】查询Student表中出生日期在1989-1-3以后的学生 select 姓名,出生日期 from Student where 出生日期>'1989-1'注:字符型或日期型的数据要用单引号引起来and ,or 【例】查询Student表中学号为1101且姓名为李明的相关信息 select * from Student where 姓名='李明' and 学号='1101'【例】查询Student表中姓名为李明或者学号为1101的相关信息 select * from Student where 姓名='李明' or 学号='1101'between…and 在…范围之内 【例】查找总学分为60和70之间的学生所有信息 select * from Student where 总学分 between 60 and 70 --(大于60小于70)【例】查找出生日期不在1980-8-26到1979-1-29的学生姓名 select 姓名,出生日期 from Student where出生日期 not between '1980-8-26 'and '1979-1- 29'* 注意时间的用法in ==or IN用于查找属性值属于指定集合的记录,与IN相对的谓词是NOT IN,in 关键字可以简化查询条件的书写 【例】查找分数为70和80的所有学生信息 use Grade select * from Student where 总学分 in(70,80)is关键字 在基本表中,如果那一列中没有输入数据,则它的值就为空,空值用一个特殊的数据NULL来表示,如果要判断某一列是否为空,不能用“=NULL”或“ NULL”来比较,只能用IS NULL或IS NOT NULL来运算 例:查询邮箱为空的学生记录 select * from Student where Email is null distinct关键字 Distinct:从返回的结果数据集合中删除重复的行 【例】查询Grade数据库中Student表中的总学分,但是不能有重复的 use Grade select distinct 总学分 from Student order by 总学分 go使用like子句进行模糊查询 like子句与通配符配合使用。Sqlserver提供4种通配符 1.%:表示任意字符 2. _:表示单个任意字符 3.[ ]:表示方括号里列出的任意一个字符. 4.[^]:表示任意一个没有在方括号里列出的字符. 基本语法: select 字段名 from 目标表 where 字段名 like 条件排序查询 order by排序:asc升;desc降 【例】查找学生的总学分以升序排列,出生日期以降序排列的学生姓名和学号 use Grade select 姓名,出生日期,总学分, 学号 from Student order by 总学分 asc ,出生日期 desc*以第一列为主序,再在第一列相等的基础上再对第二列排序;asc 默认,可省略TOP关键字 top:关键字用于指定只返回前面一定数量的数据. top n :表示返回最前面的n行. 【例】查询在Grade库中Student表中总学分最高的前5项的学生姓名 use Grade select top 5 总学分, 姓名 from Student order by 总学分 asc gotop. ..with ties 指定返回并列前N条记录 use northwind select top 5 with ties orderid, productid, quantity from [order details] order by quantity desc go* with ties必须与order by连用 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |