博客列表 >mysql CURD常用操作及预处理机制

mysql CURD常用操作及预处理机制

陈强
陈强原创
2021年02月25日 14:46:39721浏览

数据更新 update

  1. update user set age = timestampdiff(year, brithdy, now());

查询数据 select

  • 查询全部
  1. select * from user;

  • 条件查询 where
  1. select * from user where id = 1;

  • 区间查询 between … and
  1. select * from user where id between 1 and 5;

  • 集合查询 in
  1. select * from user where id in(1,2,4,5);

  • 分组查询 count() max() min() avg() sum()
  1. //count()
  2. select gender, count(*) from user group by gender;
  3. //sum()
  4. select sum(age) from user;
  5. //avg()
  6. select avg(age) from user;
  • 分组条件查询 having,不能用where
  1. select gender, count(*) from user group by gender having gender = 'male';

  • 排序 order by
  1. select * from user order by age desc;

  • 分页查询 limit
  1. select * from user order by age desc limit 5;

关联查询

  • 内连接
  1. select u.id,u.name,t.id,t.name from user as u, test as t where u.id = t.id;
  2. //简化

  • inner join … on
  1. select * from user u join test t on u.id = t.id;
  2. //简化
  3. select * from user u join test t using(id);
  4. //条件
  5. select * from user u join test t using(id) where u.id = 1;

  • 左外连接 left join
  1. select * from user u left join test t using(id);

  • 右外连接 right join
  1. select * from user u right join test t using(id);

索引

索引应该创建在经常被查询的字段,或者常出现在结果集中的字段上

  • 创建索引
  1. //普通索引
  2. create index i_name on user (name);
  3. //唯一索引
  4. create unique index unique_gender on user(gender);

预处理

  • 防止 SQL 注入攻击
  • SQL 语句中的数据,只有在执行阶段再与字段进行绑定
  1. prepare stmt from 'select id,name from user where age > ? limit ?';
  2. set @age= 20, @num = 5;
  3. execute stmt using @age, @num;

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议