MYSQL查询操作

--逻辑运算符

  • and
  • select * from classes where age >= 18 and age <= 28;
  • or
  • select * from classes where age>18 or height >=100;
  • not
  • select * form classes where not (age > 18 and gender=2);

--模糊查询(where name like 要查询的数据)

  • like
  • % 替换任意个
  • _ 替换1个
  • 查询姓名中 以“小“开始的名字
  • select * from classes where name like "小%"

--范围查询

  • in (1,3,6)表示在一个非连续的范围内
  • 查询年龄为18、34的姓名
  • select * from classes where age in (18,34);
  • not in 非连续的范围之内
  • select * from classes where age between 18 and 34;
  • not between...and..表示不在连续的范围内
  • 空判断is null和非空判断 is not null
  • select * from classes where height is null

--排序

  • order by
  • asc 从小到大排序,升序
  • desc 从大到小排序,降序
  • select * from classes where (age between 18 and 34) and gender = 1 order by age asc,name desc;

--聚合函数

  • 总数
  • -count
  • select count(*) from classes where gender = 1;
  • 最大值
  • max
  • 最小值
  • min
  • 求和
  • sum
  • 平均值
  • avg
  • round(123.23 , 1) 保留1位小数(四舍五入)

--分组(可以和聚合函数一起使用)

  • group by
  • 按照性别分组,查询所有的性别
  • select gender from classes group by gender;
  • group_concat(...)
  • 查询同种性别中的姓名
  • select group_concat(name),gender from classes group by gender;
  • having(having 类似where和group by组合使用)
  • 查询平均年龄超过30岁的性别,以及姓名 having avg(age) > 30
  • select gender,group_concat(name) from students group by gender having avg(age) > 30;

--分页

  • limit start,count
  • select * from classes limit 0,2;

--连接查询

  • inner join ... on
  • select ... from 表A inner join 表B;
  • select * from students inner join classes on students.cls_id = classes.id;
  • left join(左连接)
  • right join(右连接)
  • 以左边或者右边的表作为基准进行查询,没有的信息将以null显示

-- 子查询

  • 标量子查询:子查询返回的结果是一个数据(一行一列)
  • 列子查询:返回的结果是一列(一列多行)
  • 行子查询:返回的结果是一行(一行多列)
  • 1 查出平均身高
  • select avg(height) from students ; -- 172
  • 2 查出高于平均身高的信息
  • select * from students where height >(select avg(height) from students) ;

猜你喜欢

转载自blog.csdn.net/s201314yh/article/details/80101965