ClickHouse有2类解析器,一类是完整SQL解析器(递归式解析器),一类是数据格式解析器(快速流式解析器)。除了 INSERT 查询,其它情况下仅使用完整SQL解析器。因此ClickHouse基本兼容sql语法,同时ClickHouse也具有其独特的查询函数。
1. 数据查询
废话不多说,直接切入主题。
1.1 with子句
支持cte,即公用表表达式。如:
select pow(pow(2,2),3)
相当于 :
with pow(2,2) as a select pow(a,3)
1.定义变量
with 10 as start
select * from table where num > start;
2.调用函数
with sum(num) as bytes
select database,formatReadableSize(bytes) as format from table group by database
3.定义子查询
需注意with的子查询语句只能返回一行。
with (
select sum(num) from table
) as total_bytes
select database,(sum(num) / total_bytes) as usage from table group by database
4.子查询中重复使用with
对结果集中的usage再次使用取整函数。
with (
round(usage)
) as usage_v1
select database,usage,usage_v1
from (
with (
select sum(num) from table
) as total_bytes
select database,(sum(num) / total_bytes) as usage from table group by database
)
1.2 from子句
表示从何处读数据。对象包括:
数据表
子查询
表函数
比如从函数numbers()读取:
select number from numbers(5)
1.3 sample子句
数据采样,取部分数据进行近似计算。采用幂等设计,数据不变化,多次采样结果相同。适用MergeTree系列引擎的数据表,在建表时声明。
需注意以下几点:
按照intHash32(UserID)分布后的结果采样查询
sample by表达式必须同时包含在主键声明中
sample key 必须是int类型,否则查询报错
create table new_table(
CounterID UInt64,
UserID UInt64,
EventDate DATE
) ENGINE = MergeTree()
partition by toYYYYMM(EventDate)
order by (CounterID, intHash32(UserID))
sample by intHash32(UserID)
1.SAMPLE factor
按因子系数采样,取值支持0~1之间的小数。如果factor设置为0或者1,则效果等同于不进行数据采样。
select CounterID from new_table sample 0.1
select CounterID from new_table sample 1/10 (十进制)
查询结果需要乘以采样系数。如果因子系数为0.1,那么采样系数为10