1. 程式人生 > 其它 >8.15.5. Searching in Arrays

8.15.5. Searching in Arrays

技術標籤:PostgreSQL 13.0 Documentationpostgresql

8.15.5. Searching in Arrays 8.15.5.檢索陣列 To search for a value in an array, each value must be checked. This can be done manually, if you know the size of the array. For example: 要在陣列中搜索值,必須檢查每個值。 如果已知陣列的大小,則可以手動完成。 例如:
SELECT * FROM sal_emp WHERE pay_by_quarter[1] = 10000 OR
pay_by_quarter[2] = 10000 OR
pay_by_quarter[3] = 10000 OR
pay_by_quarter[4] = 10000;

However, this quickly becomes tedious for large arrays, and is not helpful if the size of the array isunknown. An alternative method is described in Section 9.23. The above query could be replaced by:

但是,這對於大型陣列這很快會變得很繁瑣,如果陣列的大小未知,這將無濟於事。 另一種方法在 9.24節 中描述。 上面的查詢可以替換為:
SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter);

In addition, you can find rows where the array has all values equal to 10000 with:

此外,可以使用以下命令查詢陣列的所有值均等於10000的行:
SELECT * FROM sal_emp WHERE 10000 = ALL (pay_by_quarter);

Alternatively, the generate_subscripts function can be used. For example:

或者,可以使用generate_subscripts函式。 例如:
SELECT * FROM
(SELECT pay_by_quarter,
generate_subscripts(pay_by_quarter, 1) AS s
FROM sal_emp) AS foo
WHERE pay_by_quarter[s] = 10000;
This function is described in Table 9.62. 表9.62對此函式進行了描述。 You can also search an array using the && operator, which checks whether the left operand overlaps with the right operand. For instance: 也可以使用操作符&&來檢索陣列, 該運算子檢查左運算元是否與右運算元重疊。 例如:
SELECT * FROM sal_emp WHERE pay_by_quarter && ARRAY[10000];

This and other array operators are further described in Section 9.18. It can be accelerated by an appropriateindex, as described in Section 11.2.

&&及其他陣列運算子將在 9.19節 中進一步描述。 如 第11.2節 所述,可以通過適當的索引來加速查詢。 You can also search for specific values in an array using the array_position and array_positions functions. The former returns the subscript of the first occurrence of a value in an array; the latter returns an array with the subscripts of all occurrences of the value in the array. For example: 還可以使用array_position和array_positions函式在陣列中搜索特定值。前者返回陣列中第一個出現的值的下標;後者返回陣列中包含該值的所有出現的下標。 例如:
SELECT
array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'],
'mon');
array_positions
-----------------
2
SELECT array_positions(ARRAY[1, 4, 3, 1, 3, 4, 2, 1], 1);
array_positions
-----------------
{1,4,8}

Tip 小貼士 Arrays are not sets; searching for specific array elements can be a sign of database misdesign. Consider using a separate table with a row for each item that would be an array element. This will be easier to search, and is likely to scale better for a large number of elements. 陣列不是集合; 搜尋特定的陣列元素可能是資料庫設計錯誤的標誌。考慮使用單獨的表,該表的每個行作為一個數組元素,這將更易於檢索,並且在針對大量元素時進行更好地縮放。