zoukankan      html  css  js  c++  java
  • Mysql-Sql查询汇总

    简单查询

    创建students表

    create table students(
    id int not null unique primary key auto_increment,
    name varchar(10) not null,
    class varchar(10) not null,
    grade int
    )

    添加数据

    insert into students values(0,'老1','1班',80);
    insert into students values(0,'老2','2班',90);
    insert into students values(0,'老3','3班',86);
    insert into students values(0,'老4','4班',70);
    insert into students values(0,'老5','5班',89);
    insert into students values(0,'老6','6班',93);

    查询所有数据

    select * from students

    查询指定字段

    select name,class from students

    通过as给表起别名

    select s.name,s.class from students as s

    通过as给字段起别名

    select name as 姓名,class as 班级 from students

    条件查询

    比较运算

    select * from students where class='1班'

    select * from students where grade>90

    逻辑运算

    and、or、not

    select * from students where grade<90 and class!='1班'

    模糊查询

    like%任意多个字符、_一个任意字符

    select * from students where name like '老%'

    select * from students where name like '%5'

    范围查询

    in表示非连续范围内、between...and...在一个连续范围内

    select * from students where class in('1班','3班','4班')

    select * from students where grade between 80 and 90

    空判断

    is null 与' '不同,' '为空字符串

    select * from students where grade is null

    select * from students where class=' '

    insert into students(name,class,grade) values('老7','1班',null)

    排序

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

    asc从小到大,升序,不写则为升序

    desc从大到小,降序

    select * from students order by grade

    先按grade降序、再按id升序

    select * from students order by grade desc,id 

    先按id升序、再按grade降序

    select * from students order by id,grade desc

    聚合函数

    count

    select count(*) from students

    带字段的不统计为null的数据

    select count(grade) from students

    max、min、sum、avg

    select max(grade) from students 

    select avg(grade) from students

    分组

    select sex,count(*) from students group by sex

     select grade,count(*) from students group by grade

     select class,grade,count(*) from students group by grade,class

     分组后过滤

    使用having,必须跟在group by之后

    where是用于from后的数据筛选、having是对group by的结果进行筛选

    获取部分行

    索引0开始

    select * from students order by grade limit 0,3

    分页

    每页显示m条数据,第n页的数据

    select * from students limit (n-1)*m,m

  • 相关阅读:
    nginx设置账号密码--htpasswd的使用
    Sublime Text 3安装Json格式化插件
    Visual Studio code 代码格式化整理
    安装uwsgi 报错“fatal error: Python.h: No such file or directory”
    Nginx 访问优先级配置
    Git 代码回退回退一个版本或多个版本
    SQL 常用方法例子
    SQL 常用方法函数
    FlipViewDemo
    data1是字符串?需要加上引号
  • 原文地址:https://www.cnblogs.com/katyhudson/p/12605980.html
Copyright © 2011-2022 走看看