array_filter
返回数组中与给定过滤器匹配的值。
此函数有两种形式。 lambda 采用允许更灵活的数组过滤。有关 lambda 函数的更多信息,请参见Lambda 表达式。此函数从 v2.5 开始支持。
语法
array_filter(array, array<bool>)
array_filter(lambda_function, arr1,arr2...)
-
array_filter(array, array<bool>)
返回与
array<bool>
匹配的数组中的值。 -
array_filter(lambda_function, arr1,arr2...)
返回与 lambda 函数匹配的数组中的值。
参数
array
: 要从中筛选值的数组。
array<bool>
: 用于筛选值的表达式。
lambda_function
: 用于筛选值的 lambda 函数。
使用说明
array_filter(array, array<bool>)
的两个输入参数必须为 ARRAY,并且筛选表达式可以评估为array<bool>
。array_filter(lambda_function, arr1,arr2...)
中的 lambda 函数遵循array_map()中的使用说明。- 如果输入数组为 null,则返回 null。如果筛选器数组为 null,则返回一个空数组。
示例
-
不使用 lambda 函数的示例
-- All the elements in the array match the filter.
select array_filter([1,2,3],[1,1,1]);
+------------------------------------+
| array_filter([1, 2, 3], [1, 1, 1]) |
+------------------------------------+
| [1,2,3] |
+------------------------------------+
1 row in set (0.01 sec)
-- The filter is null and an empty array is returned.
select array_filter([1,2,3],null);
+-------------------------------+
| array_filter([1, 2, 3], NULL) |
+-------------------------------+
| [] |
+-------------------------------+
1 row in set (0.01 sec)
-- The input array is null, null is returned.
select array_filter(null,[1]);
+-------------------------+
| array_filter(NULL, [1]) |
+-------------------------+
| NULL |
+-------------------------+
-- Both the input array and filter are null. Null is returned.
select array_filter(null,null);
+--------------------------+
| array_filter(NULL, NULL) |
+--------------------------+
| NULL |
+--------------------------+
1 row in set (0.01 sec)
-- The filter contains a null element and an empty array is returned.
select array_filter([1,2,3],[null]);
+---------------------------------+
| array_filter([1, 2, 3], [NULL]) |
+---------------------------------+
| [] |
+---------------------------------+
1 row in set (0.01 sec)
-- The filter contains two null elements and an empty array is returned.
select array_filter([1,2,3],[null,null]);
+---------------------------------------+
| array_filter([1, 2, 3], [NULL, NULL]) |
+---------------------------------------+
| [] |
+---------------------------------------+
1 row in set (0.00 sec)
-- Only one element matches the filter.
select array_filter([1,2,3],[null,1,0]);
+---------------------------------------+
| array_filter([1, 2, 3], [NULL, 1, 0]) |
+---------------------------------------+
| [2] |
+---------------------------------------+
1 row in set (0.00 sec) -
使用 lambda 函数的示例
-- Return the elements in x that are less than the elements in y.
select array_filter((x,y) -> x < y, [1,2,null], [4,5,6]);
+--------------------------------------------------------+
| array_filter((x, y) -> x < y, [1, 2, NULL], [4, 5, 6]) |
+--------------------------------------------------------+
| [1,2] |
+--------------------------------------------------------+