MySQL查询


  • 完整的select语句

select distinct *

from 表名

where ...

group by .. having ...

order by ..

limit start, count


  • 执行顺序为:

    from 表名

    where ...

    group by ...

    select ditinct *

    having ...

    order by ...

    limit start,count


  • 查询语句

select * from 表名;

  • 消除重复语句

select distinct 字段 from 表名;


  • 条件

select * from 表名 where ...;

  • 比较运算符

    等于=

    大于>

    大于等于>=

    小于<

    小于等于<=

    不等于!=或<>


  • 逻辑运算符

    and

    or

    not


  • 模糊查询

    like

    %表示任意多个任意字符

    _表示任意字符


  • 范围查询

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

    between ... and ...表示在一个连续的范围内


  • 注意:null与 ‘’ 是不同的

    判断is null

    判非空is not null


  • 优先级

    小括号,not,比较运算符,逻辑运算符

    and比or先运算,如果同事出现并希望先算or,需要结合()使用


聚合
  • 为了快速得到统计数据,提供了5个聚合函数

  • count(*)表示计算总行数,括号中写星与列名,结果是相同的。


select count(*) from 表名;

  • max(列)表示此列的最大值

select max(id) from students where isdelete=0;

  • min(列)表示此列的最小值

select min(id) from students where isdelete=0;

  • sum(列)表示求此列的和

select sum(id) from students where gender=0;

  • avg(列)表示求此列的平均值

select avg(id) from students where isdelete=0 and gender=0;


  • 分组

  • group by


select 列1,列2,聚合 ... from 表名 group by 列1,列2,列3...




  • having

use python3;
SELECT gender,count(*) FROM students GROUP BY gender HAVING gender=0;


use python3;
SELECT gender,count(*) as cu FROM students GROUP BY gender HAVING cu>1;

  • where是对from后面指定的表进行数据筛选,属于对原始数据的筛选。

  • having是对group by的结果进行筛选。


  • 排序

  • order by


select * from 表名

order by 列1 asc|desc,列2 asc|desc,...



use python3;
SELECT * from students where isdelete=1 and gender=1 ORDER BY id desc;

  • 分页

  • limit


select * from 表名

limit start,count

  • 从start开始,获取count条数据

  • start索引从0开始

  • 示例:分页

  • 已知:每页显示m条数据,当前显示第n页

  • 求总页数

  • python


查询总条数p1

使用p1除以m得到p2

如果整除则p2为总数页

如果不整除则p2+1为总页数

  • 求第n页的数据 mysql

limit (n-1)*m,m


原文地址:https://www.cnblogs.com/mephisto03/p/9383137.html