Blogger Information
Blog 41
fans 0
comment 0
visits 30983
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mysql CURD常用操作及预处理机制
陈强
Original
720 people have browsed it

数据更新 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;

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:数据表名称推荐使用复数,例如users,每一条记录可用user表示,这是惯例
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post