1

我正在尝试搜索匹配字符串的数组位置,我看到有一个帖子包含字符串上字符的位置,但没有包含数组的帖子,这是我想要实现的示例:

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

我想知道包含单词“potato”的元素在哪里,所以结果应该是这样的:

[1,4] 

我试图获取所有元素的长度,然后将数组转换为字符串,并搜索字符串以查看字符串匹配的位置并比较该位置是否可以进入任何数组元素长度之间,但这不是如果我在数组中的元素数量是可变的,并且在我的问题中是可变的,则可以工作。

4

1 回答 1

3

如果您想要完全匹配,请使用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}    ║
╚════╩════════╝
于 2016-04-05T12:53:22.733 回答