簡體   English   中英

字符串匹配在 PostgreSQL 9.5 數組中的位置

[英]Position of string-match in PostgreSQL 9.5 array

我正在嘗試搜索匹配字符串的數組位置,我看到有一個帖子在字符串上有一個字符的位置,但沒有一個帶有數組的帖子,這是我想要實現的示例:

array['potato-salad','cucumber-salad','eggplant-pie','potato-soup']

我想知道包含“potato”這個詞的元素在哪里,所以結果應該是這樣的:

[1,4] 

我試圖獲取所有元素的長度,然后將數組轉換為字符串,並搜索字符串以查看字符串匹配的位置並比較位置是否可以在任何數組元素長度之間,但這不會如果數組中的元素數量是可變的,則工作,而在我的問題中,它是可變的。

如果你想完全匹配使用array_positions

CREATE TABLE my_tab(ID INT, col VARCHAR(100)[]);

INSERT INTO my_tab(ID, col)
VALUES (1, array['potato-salad','cucumber-salad','eggplant-pie','potato-soup']),
       (2, array['potato']);

詢問:

SELECT *
FROM my_tab
,LATERAL array_positions(col, 'potato-salad') AS s(potato_salad_position)
WHERE s.potato_salad_position <> '{}';

輸出:

╔════╦════════════════════════════════════════════════════════╦═══════════════════════╗
║ id ║                          col                           ║ potato_salad_position ║
╠════╬════════════════════════════════════════════════════════╬═══════════════════════╣
║  1 ║ {potato-salad,cucumber-salad,eggplant-pie,potato-soup} ║ {1}                   ║
╚════╩════════════════════════════════════════════════════════╩═══════════════════════╝

如果您想使用帶有通配符的LIKE搜索,您可以使用unnest WITH ORDINALITY

SELECT id, array_agg(rn) AS result
FROM my_tab
,LATERAL unnest(col) WITH ORDINALITY AS t(val,rn)
WHERE val LIKE '%potato%'
GROUP BY id;

輸出:

╔════╦════════╗
║ id ║ result ║
╠════╬════════╣
║  1 ║ {1,4}  ║
║  2 ║ {1}    ║
╚════╩════════╝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM