首页 / 数组和 Map
ARRAY_JOIN 数组拼接成字符串
ARRAY_JOIN 用分隔符把数组元素拼成字符串,可以用第三个参数替换 NULL 元素,不传时跳过 NULL。MaxCompute、StarRocks、Doris、Spark 和 Flink 同名可用;Hologres 用 ARRAY_TO_STRING;Hive 用 concat_ws,并且只接受字符串数组。
各引擎写法
| 引擎 | 支持 | 写法 | 说明 | 依据 |
|---|---|---|---|---|
| MaxCompute | 支持 | ARRAY_JOIN(a, delimiter[, nullreplacement]) | 非 STRING 元素会先转成 STRING。没有 nullreplacement 时忽略 NULL 元素。 | 官方文档 |
| Hologres | 需改写 | ARRAY_TO_STRING(anyarray, text[, text]) | 第三个参数用于表示 NULL 元素,不指定时忽略 NULL。返回 TEXT。 | 官方文档 |
| StarRocks | 支持 | array_join(array, sep[, null_replace_str]) | 只支持一维数组,不支持 DECIMAL 元素。不传 null_replace_str 时丢弃 NULL;sep 或 null_replace_str 为 NULL 时返回 NULL。 | 官方文档 |
| Doris | 支持 | ARRAY_JOIN(arr, separator[, null_replacement]) | 2.0.0 起提供,元素先转成字符串再拼接。不传 null_replacement 时跳过 NULL;数组为 NULL 时返回 NULL。 | 官方文档 |
| Hive | 需改写 | concat_ws(SEP, array<string>) | Hive 0.9.0 起 concat_ws 可以接受字符串数组。非字符串数组要先转换元素类型。 | 官方文档 |
| Spark SQL | 支持 | array_join(array, delimiter[, nullReplacement]) | Spark 2.4.0 起提供。不传 nullReplacement 时过滤掉 NULL。 | 官方文档 |
| Flink SQL | 支持 | ARRAY_JOIN(array, delimiter[, nullReplacement]) | 数组元素必须是字符串类型。 | 官方文档 |
迁移注意事项
- Hive 的 concat_ws 只接受 array<string>,整数数组要先转换;Flink 的 ARRAY_JOIN 也要求元素是字符串。MaxCompute、Doris 会自动把元素转成字符串。
- 不传第三个参数时,各引擎都跳过 NULL 元素,结果中不会出现空位。需要保留位置时,显式传入替换字符串。
- StarRocks 不支持 DECIMAL 元素,也只支持一维数组,迁移前要检查数组类型。
示例
把标签数组拼成逗号分隔的字符串
SELECT user_id, ARRAY_JOIN(tags, ',') AS tag_str FROM user_tags;SELECT user_id, ARRAY_TO_STRING(tags, ',') AS tag_str FROM user_tags;SELECT user_id, array_join(tags, ',') AS tag_str FROM user_tags;SELECT user_id, ARRAY_JOIN(tags, ',') AS tag_str FROM user_tags;SELECT user_id, concat_ws(',', tags) AS tag_str FROM user_tags;SELECT user_id, array_join(tags, ',') AS tag_str FROM user_tags;SELECT user_id, ARRAY_JOIN(tags, ',') AS tag_str FROM user_tags;