mysql基础整理02

比较运算符 > < = >= <= !=和<>

  • !=和<>都是一个意思,都是不等于的意思

    and和or

  • and 并且&& 需要同时满足多个条件时使用
  • or 或|| 需要满足多个条件中的某一个条件时使用

    in 和 not in

    select * from emp where sal=5000 or sal=950 or sal=3000;
    两个的意思相等
    select * from emp where sal in (5000,950,3000);

    between x and y 包括xy

    模糊查询 like

  • _代表单个未知字符
  • %代表0或多个未知字符
    -举例:
    以a开头 a%
    以b结尾 %b
    包含c %c%
    第一个字符是a 倒数第二个字符是b a%b_
    匹配163邮箱 %@163.com
    任意邮箱 %@%.com

    排序

  • order by 字段名 asc/desc;

    分页查询

  • limit 跳过的条数,请求的条数(每页的条数)
  • limit (页数-1)*每页的条数,每页的条数

    函数

    concat()函数

    数值计算

          • / % 7%2 = mod(7,2)

            日期相关函数

  • 获取当前日期+时间
    select now();
  • 获取当前年月日 和 时分秒
    select curdate(),curtime();
  • 从完整的年月日时分秒中 提取年月日 和 提取时分秒
    select date(now());
    select time(now());
  • 从完整的年月日时分秒中提取时间分量 extract
    select extract(year/month/day/hour/minute/second from now());

  • 日期格式化 date_format()
    date_format(时间,格式);
    格式:
    %Y 四位年 %y 两位年
    %m 两位月 %c 一位月
    %d 日
    %H 24小时 %h 12小时
    %i 分
    %s 秒
    把默认的时间格式转成 年月日时分秒
    select date_format(now(),'%Y年%m月%d日 %H时%i分%s秒');
  • 把非标准时间格式转成标准格式 str_to_date()
    str_to_date(字符串时间,格式)
    14.08.2019 08:00:00
    select str_to_date('14.08.2019 08:00:00','%d.%m.%Y %H:%i:%s');

    聚合函数

  • 求和:sum(求和的字段)
  • 平均值:avg(字段)
  • 最大值:max(字段)
  • 最小值:min(字段)
  • 计数: count(字段) 一般写count(*) 只有涉及null值时才使用字段名

    字符串相关函数

  • char_length(str)获取字符串的长度
  • instr(str,substr) 获取substr在str中出现的位置 从1开始
  • insert(str,start,length,newstr)
  • lower(str) upper(str)
  • trim(str) 去两端空白
  • left(str,index) 从左边截取
  • right(str,index) 从右边截取
  • substring(str,index,?length) 从指定位置截取
  • repeat(str,count) 重复
  • replace(str,old,new) 替换
  • reverse() 反转

    数学相关的函数

  • floor(num) 向下取整
  • round(num) 四舍五入
  • round(num,m) m代表保留几位小数
  • truncate(num,m) 非四舍五入
  • rand() 随机数0-1
    获取 0-5的随机整数
    select floor(rand()6);
    获取3-6的随机整数 0-3 + 3
    select floor(rand()
    4)+3;

    分组查询

  • group by 字段名,字段名

    having

  • where后面只能写普通字段的条件,不能写聚合函数的条件
  • having一般要和分组查询结合使用,后面写聚合函数的条件,having写在分组查询的后面

    子查询(嵌套查询)

    关联查询

  • 同时查询多张表的数据的查询方式称为关联查询

    等值连接和内连接

  • 关联查询的两种查询方式:
  1. 等值连接: select * from A,B where A.x=B.x and A.age=18;
  2. 内连接:select * from A join B on A.x=B.x where A.age=18;
  3. 外链接(左外和右外): select * from A left/right join B on A.x=B.x where A.age=18;

    SQL分类:

    1. DDL数据定义语言 包括:create drop alter truncate 不支持事务
    2. DML数据操作语言 包括:insert delete update select 支持事务
    3. DQL数据查询语言 包括:select
    4. TCL事务控制语言 包括:begin commit rollback savepoint xxx,rollback to xxx;
    5. DCL数据控制语言 分配用户权限相关SQL

猜你喜欢

转载自www.cnblogs.com/Libbo/p/10483029.html
今日推荐