如果您想要完全匹配,请使用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} ║
╚════╩════════╝