详解 ClickHouse 的 SQL 操作

传统关系型数据库(以 MySQL 为例)的 SQL 语句,ClickHouse 基本都支持

一、插入

--语法:
insert into table_name values(xxxxxx),(yyyyyyy),...;

insert into table_name select xxxxx from table_name2 where yyyyy;

二、更新和删除

作为 OLAP 数据库,ClickHouse 本身不太擅长更新和删除操作,它提供了 Delete 和 Update 的能力,不同于 OLTP 数据库的更新和删除操作,这类操作被称为 Mutation 查询,它可以看做 Alter 的一种。

--更新
alter table table_name update column=value where condition;

--删除
alter table table_name delete where condition;
  • Mutation 语句是一种很“重”的操作,而且不支持事务
  • ClickHouse 更新和删除的本质操作是将原有的分区重新创建一份并把更新或删除后的新数据写入,然后将原有分区打上逻辑上的失效标记,此时原有数据依然存储在磁盘,直到触发分区合并的时候,才会真正删除旧数据释放磁盘空间
  • 实际生产中不建议对 ClickHouse 的表数据进行更新和删除

三、查询

1. 基本查询

select columns from table_name where conditions group by column order by column;

--1. 支持子查询
select columns from (select columns from table_name where conditions);

--2. 支持 CTE(Common Table Expression 公用表表达式 with 子句)
with table_name2 as (
	select columns from table_name where conditions
)

select * from table_name2

2. 关联查询

支持各种 JOIN,但是 JOIN 操作无法使用缓存,所以即使是两次相同的 JOIN 语句,ClickHouse 也会视为两条新 SQL

3. 基本函数

--条件判断
if(condition, then, else) --条件值为非0则 then 否则 else
multiIf(cond1, then1, cond2, then2, ...., else) --类似于 case when then else end 函数

4. 多维分析函数

--with rollup:上卷
group by a,b with rollup --统计的维度组合为 (), a, (a,b)


--with cube:多维分析
group by a,b with cube --统计的维度组合为 (), a, b, (a,b)

--with totals:总计
group by a,b with totals --统计的维度组合为 (), (a,b)

四、alter 操作

--新增字段
alter table table_name add column col_name col_type after col_name1;

--修改字段类型
alter table table_name modify column col_name new_col_type;

--删除字段
alter table table_name drop column col_name;

五、导出数据

更多支持格式参照:https://clickhouse.tech/docs/en/interfaces/formats/

#将查询出的数据导出为 csv 文件
clickhouse-client --query "select * from t_order_mt where create_time='2020-06-01 12:00:00'" --format CSVWithNames > /opt/module/data/rs1.csv
  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值