【问题标题】:How to use ClickHouse partition value in SQL query?如何在 SQL 查询中使用 ClickHouse 分区值?
【发布时间】:2021-11-26 23:28:48
【问题描述】:

我有一个带有元组分区的表:(0, 0)(0, 1)(1, 0)(1, 1)(2, 0)(2, 1)(3, 0)、...

CREATE TABLE my_table
(
    id Int32,
    a Int32,
    b Float32,
    c Int32
)
ENGINE = MergeTree
PARTITION BY
(
    intDiv(id, 1000000),
    a < 20000 AND b > 0.6 AND c >= 100
)
ORDER BY id;

我只需要分区 (&lt;any number&gt;, 1) 的行,我正在寻找一种在查询中使用分区值的方法,例如

SELECT *
FROM my_table
WHERE my_table.partition[2] == 1;

ClickHouse有这样的功能吗?

【问题讨论】:

    标签: clickhouse


    【解决方案1】:

    在版本 21.6 中添加了虚拟列 _partition_id_partition_value 可以帮助您:

    SELECT
        *,
        _partition_id,
        _partition_value
    FROM my_table
    WHERE (_partition_value.2) = 1
    

    【讨论】:

      【解决方案2】:

      还有什么问题

      where (a < 20000 AND b > 0.6 AND c >= 100) = 1
      

      ???

      insert into my_table select 1, 3000000, 0, 0 from numbers(100000000);
      insert into my_table select 1, 0, 10, 200 from numbers(100);
      
      SET send_logs_level = 'debug';
      set force_index_by_date=1;
      
      select sum(id) from my_table where (a < 20000 AND b > 0.6 AND c >= 100) = 1;
                 
      ...Selected 1/7 parts by partition key...
      
      ┌─sum(id)─┐
      │     100 │
      └─────────┘
      1 rows in set. Elapsed: 0.002 sec.
      
      

      虽然(_partition_value.2) = 1 会更快,因为它不需要读取 a、b、c 列进行过滤。

      【讨论】:

      • 扫描行数的问题。分区值的条件将跳过其他分区中的行而不进行任何检查。
      • 由于分区修剪,CH 只读取相关分区。
      猜你喜欢
      • 2021-05-15
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2017-03-25
      相关资源
      最近更新 更多