mysql日常使用总结(持续更新中)

记录一些日常的mysql常用的使用, 方便随用随查。

一、表结构

1.1 查看表结构

  • 方式1: 可以查看建表语句,完整的表结构。
show create table table_name;
  • 方式2:可以比较好的筛选自己要查的表信息,方便整理表结构文档。
# 查询表所有列信息
select * 
from information_schema.columns
where table_schema = 'db' #表所在数据库
and table_name = 'tablename' ; #你要查的表

# 查询需要的信息
select
    column_name, column_type, column_comment,is_nullable
from information_schema.columns
where table_schema = 'o2o_monitor' #表所在数据库
and table_name = 'dws_o2o_overdue_stat' ; #你要查的表

1.2 表操作

1.2.1 表重命名

Rename table table_old to table_new
OR
alter table table_old Rename to table_new

1.2.2 修改表字段,包括名称、类型、备注等

# 增加字段
alter table table_name add column_new bigint(20)  DEFAULT NULL COMMENT '备注' After somecolumn;

# 修改字段
alter table competitor_goods change column_old column_new bigint(20)  DEFAULT NULL COMMENT '备注';

1.2.3 复制表结构

create table table_new like table_old;

1.2.4 索引

# 删除索引
ALTER TABLE table_name drop index appid_idx

# 添加索引
ALTER TABLE table_name ADD INDEX appid_idx (apply_id)

二、SQL使用

2.1 sql执行顺序:

SQL Select语句完整的执行顺序:

  1. from子句组装来自不同数据源的数据;
  2. where子句基于指定的条件对记录行进行筛选;
  3. group by子句将数据划分为多个分组;
  4. 使用聚集函数进行计算;
  5. 使用having子句筛选分组;
  6. 计算所有的表达式;
  7. 使用order by对结果集进行排序。
  8. select 集合输出。

2.2 更新记录update

2.2.1 更新记录建议事务操作

select *  from order where order_id=1231540

-- 事务开始
BEGIN

-- 更新
update order
set order_date = date_sub(order_date, interval 9 day) 
where order_id=1231540

-- 校验
select *  from order where order_id=1231540

-- 错误回滚
ROLLBACK

-- 正确提交
COMMIT

2.2.2 关联表更新

要更新的数据不能直接找到,需要做表关联才能找到

update order o
(left) join user u
on o.user_id = u.id
set o.order_date = date_sub(o.order_date, interval 9 day) 
where u.user_name='张三'

猜你喜欢

转载自www.cnblogs.com/zhanbingliu/p/10699701.html