天天看点

数据库之DQL操作数据库

查询表中数据(简单查询)

  1. 往表中添加数据,语法格式:
    • -- 往text3表中添加数据
      insert into text3 values("11","22","33","44");
                 
  2. 简单查询
    • 执行顺序:
      • from–>where–>group by -->having–>select–>order by
    • 查询指定表中所有数据
    • -- 查询指定表中所有数据
      select * from 表名;
      
      select * from text3;
                 
    • -- 查询部分字段,字段名中间用逗号隔开
      select 字段名,字段名 from 表名;
      
      select name,price from text3;
                 
    • -- 可以用as给字段名起一个别名,方便查看 如:
      select 字段名 as "新的字段名", 字段名 as "新的字段名" from text3
      
      select name as "书名", price as "价格" from text3
                 
    • 使用去重关键字 distinct
    • -- 去除重复操作,将不重复的值筛选出来
      select distinct 字段名 from 表名;
      
      select distinct price from text3;
                 
  3. 运算查询:把text3表中的价格添加100
    • select name,price + 100 from text3
                 

条件查询

如果查询语句中没有设置条件,就会查询所有的行信息,实际应用中,一定要指定查询条件,对记录进行过滤

  1. 语法格式:
    • -- 先取出表中的每条数据,满足条件的数据就返回,不满足就过滤掉
      select 列名 from where 条件表达式
                 
  2. 比较运算符
    • 运算符 说明
      ,>, < ,<=,>=,=,<>,!= 大于,小于,大于(小于)等于,不等于 (<>这个也为不等于符号)
      between…and…

      显示在某一个区间的值

      例如:100-200之间:between 100 and 200

      in(集合)

      集合表示多个值,使用逗号分隔,例如:name in (悟空,八戒)

      in中的每个数据都会最为一次条件,只要满足条件就会显示

      like"%张%"

      模糊查询,查询所有名字里带张的,例如

      where name like"%张%“;

      如果只想查询名字由某个字开头的,执行下面命令where name like"王%”;

      is null 查询某一列为null的值,注意:不能写 = null
    • 运算符 说明
      And && 多个条件同时成立
      Or || 多个条件任一成立
      Not 条件不成立,取反
    • 实际运用
    • -- 条件运算查询
      -- 查询某个比表中某一列为null的值,关键字is null
      select * from student where sid is null;
      
      -- 查询某个表中某一列大于某个值的值
      select * from text3 where price > 70;
      
      -- 查询某个表中某一列小于等于某个值的值
      select * from text3 where price <= 70;
      
      -- 查询某个表中某一列不等于某个值的值,以下两种方法一致
      select * from text3 where price <> 72;
      select * from text3 where price != 72;
      
      -- 查询某个表中某一列的值在某个区间之间, 关键字between...and...
      select * from text3 where price between 30 and 60;
      
      -- 模糊查询,查找某个表某一列中有关写入的字符的所有选项,关键字 like"%查询的字符%"
      select * from text3 where content like "%东野圭吾%";
      
      -- 模糊查询2,查找某个表某一列中有关写入的字符开头的所有选项,关键字 like"查询字符的开头%"
      select * from text3 where content like "东%";
      
      -- 集合in,查询某个表中某一列存在集合里的所有字符或数字
      select * from text3 where content in ("东野圭吾","吴承恩");
      select * from text3 where price in (102,72,34);