检索(查询)数据

关键字

  • DISTINCT 唯一性 检索出数据库中所有不重复的字段
    select distinct title,content from dandan;
    
  • LIMIT 限制检索数量
    select * from dandan limit 3;
    
  • OFFSET 偏移数量
    select * from dandan offset 2;
    //返回偏移数量
    
  • ORDER BY 按照列字段排序
    select * from dandan order by content;
    

    DESC/ASC 降序/升序排列

检索条件

WHERE 关键字指定查询条件

  • 组合查询 AND 与操作 代表两个条件都需要满足
    select * from dandan where id=1 and title = '你好';
    //检索出所有id=1并且title为你好的内容
    

    OR 或操作 两者满足其一

    select * from dandan where title = '蛋蛋' or content='蛋蛋';
    //检索出所有title为蛋蛋或者content为蛋蛋的内容
    

    IN 指定条件范围 只有满足指定条件范围的才能被查询

    select * from dandan where content IN ("你好","蛋蛋");
    //查询所有content为你好或者蛋蛋的数据
    

    NOT 取否操作 否定之后跟随的条件

    select * from dandan where NOT content="蛋蛋";
    等同于
    select * from dandan where content!="蛋蛋";
    

通配符查询(模糊查找)

LIKE 关键字 类似于中文中的像 只需要满足像这个条件就能被匹配

  • % 匹配任意长度 任意字符
    select * from dandan where title like "%蛋%";
    //检索所有title中包含蛋的字符串
    
  • _ 匹配单个字符
    select * from dandan where title like "_蛋";
    //匹配所有两个字,后一个字为蛋的内容
    
  • [] 匹配自定位置的字符集
    select * from dandan where content like ["你","蛋"]_
    //检索所有content以你或者蛋开头的两字内容
    
  • regexp 模糊匹配任意长度的包含某字符的结果
    select * from dandan where content regexp '你好';
    

<font color=yellow>pay attention: 模糊匹配的性能相对低,应尽量先以精确查找为主</font>

对字段使用函数

字符串处理

  • trim(),ltrim(),rtrim() 去除空格
    select trim(content) from dandan where id=2;
    //对结果删除空格
    
  • concat(str1,str2,…strn) 连接字符串
    select concat(title,content) from dandan where id=1;
    //检索出结果并连接title和content
    
  • REVERSE(str)反转字符串
    select reverse(title)  from dandan;
    
  • UPPER(str),LOWER(str) 返回大/小写的字符串
    select upper(title) from dandan;
    

    时间处理

  • day(date) 返回一个日期的天数部分
  • year(date) 返回一个日期的年数部分
  • month(date) 返回一个日期的月份部分
  • time(date) 返回一个日期的时间部分
  • datefweek(date) 返回一个日期是星期几
  • datediff(date1,date2)返回两个日期的天数差
  • date(date) 返回一个日期的日期部分
    select date(date) from dandan;
    

数字处理(对列名做处理)

  • max() 最大值
  • min() 最小值
  • avg() 平均值
  • sum() 总和
  • count() 总数
    select sum(id) from dandan;