ClickHouse:从同列名的select中访问源列
Posted
技术标签:
【中文标题】ClickHouse:从同列名的select中访问源列【英文标题】:ClickHouse: access to the source column from select with the same column name 【发布时间】:2019-01-29 16:25:43 【问题描述】:当我在 SELECT 块中具有相同的列名时,我无法访问 WHERE 块中的源列值。
我需要在表 test.test
上绑定 MATERIALIZED VIEW,该表聚合记录 WHERE idx = 1
并将新记录推送到具有不同 idx
值的同一表 test.test
。
create table test.test (
idx UInt8,
val Int64
) engine Memory()
insert into test.test (idx, val)
values
(toUInt8(1), toInt64(1)),
(toUInt8(1), toInt64(2)),
(toUInt8(1), toInt64(3))
-- Not working
select 2 as idx, sum(val) as val
from test.test
where idx = 1
-- Working fine, but not allowed with materialized view
select _idx as idx, val
from (
select 2 as _idx, sum(val) as val
from test.test as t
where t.idx = 1
)
预计
┌─idx─┬─val─┐
│ 2 │ 6 │
└─────┴─────┘
实际
┌─idx─┬─val─┐
│ 2 │ 0 │
└─────┴─────┘
【问题讨论】:
【参考方案1】:试试这个查询(只要考虑到求和将应用于一包插入的数据,而不是应用于表 test.test 中的所有行。换句话说,视图将包含多个idx==2 的行):
CREATE MATERIALIZED VIEW test.test_mv TO test.test AS
SELECT
toUInt8(2) AS idx,
val
FROM
(
SELECT sum(val) AS val
FROM test.test
WHERE idx = 1
)
我建议使用更适合您的情况的 SummingMergeTree 表引擎:
CREATE MATERIALIZED VIEW IF NOT EXISTS test.test_mv2
ENGINE = SummingMergeTree
PARTITION BY idx
ORDER BY idx AS
SELECT
idx,
sumState(val) as sum
FROM test.test
GROUP BY idx;
SELECT
idx,
sumMerge(sum)
FROM test.test_mv2
GROUP BY idx;
【讨论】:
以上是关于ClickHouse:从同列名的select中访问源列的主要内容,如果未能解决你的问题,请参考以下文章