mysql数据操作

1. 插入数据

# 向表中指定字段中添加值
> insert into 表 (字段1,字段2,字段3) values (值1,值2,值3);
# 向表中所有字段添加值
> insert into 表 values (值1,值2,值3,值4...);

注:字符串和日期类型的数据,必须使用单引号括起来。

2. 修改数据

> update 表 set 字段1=值1,字段2=值2 where 条件;

修改字段1和字段2的值
 * 如果没有where,默认修改所有数据
 * 如果有where,修改符合条件的数据

2. 删除数据

> delete from 表 where 条件;

* 如果没有where,默认删除所有数据
* 如果有where,删除符合条件的数据

删除所有数据
  delete from 表;
   * 一行一行的删
   * 支持事务操作
  truncate 表;
   * 先删除整个表,再创建一个与原来一样的表

3. 查询数据

# 查询所有字段
> select * from 表;
# 查询指定字段
> select 字段1,字段2,字段3 from 表;
# 过滤重复字段
> select DISTINCT 字段1  from 表;
# 使用别名查询字段
> select (字段+字段2+字段3) as 别名 from 表;
# 条件查询字段
> select * from 表 where 条件;

条件
where 子句中的符号:
>   <   <=   >=   =   <> (不等于)
in   – 表示的范围
like   – 模糊查询
and   – 与
or   – 或
not  – 非
between … and – 在…之间

# 查询一条数据,条件是数学=88
> select * from stu where math = 88;
 
# 查询结果可能是多条数据,数学成绩
> select * from stu where math in (18,88,90);

# _ 占位符,代表一个位置。结果:张飞 张三 张X  张XX(不符合)
> select * from stu where username link '张_';

# %占位符,代表多个位置。结果是姓张的都可以
> select * from stu where username link '张%';

# like '%张';      -- 以张结尾
# like '%张%';     -- 只要包含张

排序
order by 字段 asc | desc;
asc    – 升序(默认)
desc   – 降序


order by 放在select 的语句结尾。

> select * from xx where xx order by xx;

聚集函数
count()  – 求数量
sum()   – 求某一列的和,只对数值类型起作用
avg()   – 求平均分
max()   --求最大值
min()   – 求最小值

# 某一列数据行的总数
> select conut(*) | count(列名) from 表;

# 统计一个班级数学总成绩
> select sum(math) from stu;

# 求一个班级总分平均分
> select avg(math+english+chinese) from stu;

# 求一个班级总分最高分和最低分
> select max(math+english+chinese) from stu;
> select min(math+english+chinese) from stu;

分组查询
select * from stu; --查询所有数据,默认是一组。
使用关键字 group by sex 根据字段进行分组。

  • 如果有分组,where 是分组之前的条件过滤,having 是分组后的条件
  • where 关键字后不能使用聚集函数,而having可以使用聚集函数!
# 按商品分组,以组为单位,显示每一组商品的总价
> select product,sum(price) from orders group by product;

# 按商品分组,以组为单位,并且每一组商品的总价大于100的商品
> select product,sum(price) from orders group by product having sum(price) > 100;

# 商品价格大于95, 按商品分组,以组为单位,并且每一组商品的总价大于100的商品
> select product,sum(price) from orders where price >95 group by product having sum(price) > 100;

总结
select … from … where … group by … having … order by …

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值