查询之条件语句

条件语句

  • 使用where子句对表中的数据筛选,符号条件的数据会出现在结果集中
  • 语法如下:
select 字段1,字段2... from 表名 where 条件;
例:
select * from students where id=1;
  • where后面支持多种运算符,进行条件的处理
    • 比较运算
    • 逻辑运算
    • 模糊查询
    • 范围查询
    • 空判断

比较运算符

  • 等于: =
  • 大于: >
  • 大于等于: >=
  • 小于: <
  • 小于等于: <=
  • 不等于: != 或 <>

例1:查询小乔的年龄

select age from students where name='小乔'

例2:查询20岁以下的学生

select * from students where age<20

例3:查询家乡不在北京的学生

select * from students where hometown!='北京'

练习:

1、查询学号是'007'的学生的身份证号
2、查询'1班'以外的学生信息
3、查询年龄大于20的学生的姓名和性别

逻辑运算符

  • and
  • or
  • not

例1:查询年龄小于20的女同学

select * from students where age<20 and sex='女'

例2:查询女学生或'1班'的学生

select * from students where sex='女' or class='1班'

例3:查询非天津的学生

select * from students where not hometown='天津'

练习:

1、查询河南或河北的学生
2、查询'1班'的'上海'的学生
3、查询非20岁的学生

模糊查询

扫描二维码关注公众号,回复: 9031529 查看本文章
  • like
  • %表示任意多个任意字符
  • _表示一个任意字符

例1:查询姓孙的学生

select * from students where name like '孙%'

例2:查询姓孙且名字是一个字的学生

select * from students where name like '孙_'

例3:查询叫乔的学生

select * from students where name like '%乔'

例4:查询姓名含白的学生

select * from students where name like '%白%'

练习:

1、查询姓名为两个字的学生
2、查询姓百且年龄大于20的学生
3、查询学号以1结尾的学生

范围查询

  • in表示在一个非连续的范围内

例1:查询家乡是北京或上海或广东的学生

select * from students where hometown in('北京','上海','广东')
  • between ... and ...表示在一个连续的范围内

例2:查询年龄为18至20的学生

select * from students where age between 18 and 20

练习:

1、查询年龄在18或19或22的女生
2、查询年龄在20到25以外的学生

空判断

  • 注意:null与''是不同的
  • 判空is null

例1:查询没有填写身份证的学生

select * from students where card is null
  • 判非空is not null

例2:查询填写了身份证的学生

select * from students where card is not null
发布了240 篇原创文章 · 获赞 77 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/dpl12/article/details/104196898
今日推荐