Mysql使用小技巧总结

# 1.创建带分区的表
DROP TABLE IF EXISTS 表名;
CREATE TABLE 表名 (
date_id date DEFAULT NULL COMMENT '日期',
字段二 varchar(100) DEFAULT NULL)
ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY RANGE ( TO_DAYS(date_str) ) (
PARTITION p20220711 VALUES LESS THAN (738712),
PARTITION p20220712 VALUES LESS THAN (738713),
PARTITION p20220713 VALUES LESS THAN (738714)
);
# 2.增加分区,注意数字与新建时匹配
ALTER TABLE 表名 ADD PARTITION (PARTITION p20220815 VALUES LESS THAN (TO_DAYS ('2022-08-16')));
ALTER TABLE 表名 ADD PARTITION (PARTITION p20220816 VALUES LESS THAN (TO_DAYS ('2022-08-17')));
# 3.删除分区
删除分区:
ALTER TABLE 表名 DROP PARTITION p20180718;
# 4.取group by后数据的分组前2
select date_id,msisdn,"home" as area_type from user_resident a where (select count(1) from user_resident where msisdn=a.msisdn and total_traffic>=a.total_traffic)<=2;
# 5.查看建表语句:
show create table 表名;
# 6.单独sum和多项直接sum的结果不一样的原因
可能是因为某一行有null值,直接sum多项值时会抛弃有null值的行
# 7.后期增加表分区,date_str必须为date类型
alter table dws_college_traffic_user_70_d partition by range columns(date_str)(
    partition p20230530 values less than('20230530'),
   partition p20230531 values less than('20230531'),
   partition p20230601 values less than('20230601'),
   partition p20230602 values less than('20230602'),
   partition p20230603 values less than('20230603')
);
# 8.增加uuid 23位字符+数字
update dws_college_traffic_user_70_d set id=replace(UUID(),'-', '') where date_str='20230530';
# 9.mysql修改server_uuid
vim /var/lib/mysql/auto.cnf
10.查询事务及锁表情况

SHOW PROCESSLIST;
11.两个表关联更新其中一张表的字段为另一张表的字段
update name_d a, cfg_d b set a.id=b.ic where upper(a.sid)=b.cid and a.date_str>='2023-06-13' and a.date_str<='2023-07-05';
12.更新表a的d列为b/c,并且b或者c可能为0,避免除数为0
UPDATE a SET d = IF(c <> 0, b / c, 0);

你可能感兴趣的:(Mysql,mysql,数据库)