您的位置:首页 > 其它

P5 查询、order by、between and、in

2019-08-08 17:14 141 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/xinglingdi/article/details/98763889

  • 查询某数据库中的所有表名

    [code]--查询数据库表名
    select * from information_schema.tables

     

  • 为表起别名as 

表名和列名,最好为英文的

[code]select * from ClassInfo as CI
--将表ClassInfo重新命名为CI,方便查询

--as也可以省去
select * from ClassInfo CI
  •  查询全部列,查询指定列

[code]--将表StudentsInfo中是所有列
select * from StudentsInfo

--查询表中的学生的名字和年龄
select SName,SAge from StudentsInfo

--也可以为列名重新命名名字
select SName as name ,SAge as age from StudentsInfo

--as可以省去
select SName name ,SAge age from StudentsInfo

--也可以用表名.列名查询
select StudentsInfo.SName, StudentsInfo.SAge

--表名太长,可以先对表起别名再用上面的办法
select SI.SName, SI.SAge from StudentsInfo as SI
  • 行筛选、查询前n行的数据

[code]--查询前两行的数据
select top 2* from StudentsInfo

--查询前百分之多少
select top 10 percent * from StudentsInfo
  • 排序

 asc表示由小到大,desc表示由大到小

[code]--在查询后面用order by指定查询方式
select * from StudentsInfo
order by SNo asc     --按学号从小到大

--若有相同的时,可以指定两个条件,先按第一个条件排序,相同时按第二个
select  * from StudentsInfo
order by SBirthday desc, SNo asc
  • 消除重复行

 关键字:distinct

[code]--在查询时看一下都有什么班级,总共有几个班级,可以把重复的去掉
select distinct CName from StudentsInfo

between    and    取一个联系的区间

例如取出学号在10-15之间的同学的信息

[code]--编号取出10-15之间同学的信息
select * from StudentsInfo
where SNo between 10 and 15             --between是连续

--逻辑and,针对同一列时最好用between,不同列的条件时,逻辑and更好
select * from StudentsInfo
where SNo>= 10 and SNo <= 15

--取出在1或3班的学生
select * from StudentsInfo
where CNo in(1,3)                       --in用在不连续时

select * from StudentInfo
where CNo = 1 or CNo = 3

模糊查询

%表示0到多个任意字符,_表示1个任意字符,[]表示某范围内的一个字符

[code]--模糊查询
--查询名字中包含迪的学生信息
select * from StudentsInfo
where SName like '%迪%'

--查询姓徐的学生信息
select * from StudentInfo
where SName like '徐%'

--查询姓马并且两个字的学生
select * from StudentsInfo
where SName like '马_'

--查询电话号码第二位为5-9的学生信息
select * from StudentsInfo
where SPhone like '1[5-9]%'
--where SPhone like '1[579]%'

--查询电话号码第二位为0-4的学生信息
select * from StudentsInfo
where SPhone like '1[^5-9]%'
--where SPhone like '1[0-4]%'

 null的判断

[code]--修改第4和第5行的电话号码为null
update StudentsInfo set SPhone = null
where SNo in(4,5)

--查询电话为null的学生信息
select * from StudentsInfo
where SPhone is null
--where SPhone is not null
  • 优先级

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐