详解 ClickHouse 的 SQL 操作

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

一、插入

sql 复制代码
--语法:
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 的一种。

sql 复制代码
--更新
alter table table_name update column=value where condition;

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

三、查询

1. 基本查询

sql 复制代码
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. 基本函数

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

4. 多维分析函数

sql 复制代码
--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 操作

sql 复制代码
--新增字段
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/

shell 复制代码
#将查询出的数据导出为 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
相关推荐
DMD1685 分钟前
AI赋能旅游与酒店业:技术逻辑与开发实践解析
大数据·人工智能·信息可视化·重构·旅游·产业升级
爱吃面条的猿19 分钟前
MySQL 随机日期/时间生成
数据库·mysql
2501_9399090524 分钟前
Mysql 主从复制、读写分离
数据库·mysql
潇湘秦32 分钟前
ORACLE_PDB_SID和ORACLE_SID的区别
数据库·oracle
Elastic 中国社区官方博客1 小时前
Elasticsearch 中使用 NVIDIA cuVS 实现最高快 12 倍的向量索引速度:GPU 加速第 2 章
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索·数据库架构
0***86331 小时前
SQL Server2019安装步骤+使用+解决部分报错+卸载(超详细 附下载链接)
javascript·数据库·ui
wstcl1 小时前
通过EF Core将Sql server数据表移植到MySql
数据库·mysql·sql server·efcore
jqpwxt1 小时前
启点智慧景区多商户分账系统,多业态景区收银管理系统
大数据·旅游
聪聪那年221 小时前
Oracle 11g windows 10安装与卸载
数据库·oracle
jkyy20141 小时前
线上线下融合、跨场景协同—社区健康医疗小屋的智能升级
大数据·人工智能·物联网·健康医疗