clickhouse查询语法--array join

array join

array join子句允许在数据表的内部,与数组或嵌套类型的字段进行join操作,从而将一行数组展开为多行,类似于hive中的exploded炸裂函数的功能

create table tb_array_join(id Int8,hobby Array(String))engine=Log;
insert into tb_array_join values
(1,['eat','drink','sleep']),
(2,array('study','sport','read'));

select * from tb_array_join;
┌─id─┬─hobby────────────────────┐
│  1['eat','drink','sleep']  │
│  2['study','sport','read'] │
└────┴──────────────────────────┘

select h from tb_array_join array join hobby as h;
┌─h─────┐
│ eat   │
│ drink │
│ sleep │
│ study │
│ sport │
│ read  │
└───────┘

select id,hobby,arrayEnumerate(hobby) as indexs from tb_array_join;
┌─id─┬─hobby────────────────────┬─indexs──┐
│  1['eat','drink','sleep'][1,2,3] │
│  2['study','sport','read'][1,2,3] │
└────┴──────────────────────────┴─────────┘

insert into tb_array_join values(3,['run','jump']);
select id,hobby,arrayEnumerate(hobby) as indexs from tb_array_join;
┌─id─┬─hobby────────────────────┬─indexs──┐
│  1['eat','drink','sleep'][1,2,3] │
│  2['study','sport','read'][1,2,3] │
└────┴──────────────────────────┴─────────┘
┌─id─┬─hobby──────────┬─indexs─┐
│  3['run','jump'][1,2]  │
└────┴────────────────┴────────┘

或者
with arrayEnumerate(hobby) as index 
select id,hobby,index from tb_array_join; 
┌─id─┬─hobby──────────┬─index─┐
│  3['run','jump'][1,2] │
└────┴────────────────┴───────┘
┌─id─┬─hobby────────────────────┬─index───┐
│  1['eat','drink','sleep'][1,2,3] │
│  2['study','sport','read'][1,2,3] │
└────┴──────────────────────────┴─────────┘

select id,hobby,arrayEnumerate(hobby) as idx,h,xx 
from tb_array_join array join hobby as h,idx as xx;
┌─id─┬─hobby────────────────────┬─idx─────┬─h─────┬─xx─┐
│  1['eat','drink','sleep'][1,2,3] │ eat   │  1 │
│  1['eat','drink','sleep'][1,2,3] │ drink │  2 │
│  1['eat','drink','sleep'][1,2,3] │ sleep │  3 │
│  2['study','sport','read'][1,2,3] │ study │  1 │
│  2['study','sport','read'][1,2,3] │ sport │  2 │
│  2['study','sport','read'][1,2,3]read3 │
└────┴──────────────────────────┴─────────┴───────┴────┘
┌─id─┬─hobby──────────┬─idx───┬─h────┬─xx─┐
│  3['run','jump'][1,2] │ run  │  1 │
│  3['run','jump'][1,2] │ jump │  2 │
└────┴────────────────┴───────┴──────┴────┘

简化一下
select id,h,xx from tb_array_join array join hobby as h,arrayEnumerate(hobby) as xx;
┌─id─┬─h─────┬─xx─┐
│  1 │ eat   │  1 │
│  1 │ drink │  2 │
│  1 │ sleep │  3 │
│  2 │ study │  1 │
│  2 │ sport │  2 │
│  2read3 │
└────┴───────┴────┘
┌─id─┬─h────┬─xx─┐
│  3 │ run  │  1 │
│  3 │ jump │  2 │
└────┴──────┴────┘

你可能感兴趣的:(Clickhouse,clickhouse)