ClickHouse 提供了 Delete 和 Update 的能力,这类操作被称为 Mutation 查询,它可以看做 Alter 的一种。
虽然可以实现修改和删除,但是和一般的 OLTP 数据库不一样,Mutation 语句是一种很“重”的操作,而且不支持事务。
“重”的原因主要是每次修改或者删除都会导致放弃目标数据的原有分区,重建新分区。所以尽量做批量的变更,不要进行频繁小数据的操作。
1)删除操作
alter table t_order_smt delete where sku_id ='sku_001';
2)修改操作
alter table t_order_smt update total_amount = toDecimal32(2000.00,2) where id =102;
Mutation 语句分两步执行,同步执行的部分其实只是进行新增数据,新增分区并把旧分区打上逻辑上的失效标记。直到触发分区合并的时候,才会删除旧数据释放磁盘空间,一般不会开放这样的功能给用户,由管理员完成。
实现高性能update或delete的思路:
create table A ( a xxx, b xxx, c xxx, _sign UInt8, _version UInt32 )
==> 更新 :
插入一条新的数据, _version + 1
=》 查询的时候加上一个过滤条件, where version最大
==> 删除:
_sign, 0表示未删除,1表示已删除, 同时 version + 1
=》 查询的时候加上一个过滤条件, where _sign=0 and version最大
==> 时间久了,数据膨胀了
==》 类似合并机制,怎么把过期数据清除掉
3)查询操作
➢ 支持子查询
➢ 支持 CTE(Common Table Expression 公用表表达式 with 子句)
➢ 支持各种 JOIN,但是 JOIN 操作无法使用缓存,所以即使是两次相同的 JOIN 语句,
ClickHouse 也会视为两条新 SQL
➢ 窗口函数(官方正在测试中...不确定再更新)
➢ 不支持自定义函数
➢ GROUP BY 操作增加了 with rollup\with cube\with total 用来计算小计和总计。
with rollup(上卷):从右至左去掉维度进行小计
with cube(多维分析) : 从右至左去掉维度进行小计,再从左至右去掉维度进行小计
维度是a,b
rollup:上卷
group by
group by a
group by a,b
cube:多维分析
group by a,b
group by a
group by b
group by
total:总计
group by a,b
group by
相当于:
select xxxx from xxx group by a,b
union all
select xxxx from xxx group by a
union all
select xxxx from xxx group by b
union all
select xxxx from xxx
5)alter 操作
1)新增字段
alter table tableName add column newcolname String after col1;
2)修改字段类型
alter table tableName modify column newcolname String;
3)删除字段
alter table tableName drop column newcolname;
导出数据
clickhouse-client --query "select * from t_order_mt where
create_time='2020-06-01 12:00:00'" --format CSVWithNames>
/opt/module/data/rs1.csv