[英]Select rows from table with specific string value endings from list
I have a table with two columns item_name , value where item_names looks like "abracadabra_prefix.tag_name".我有一个包含两列item_name的表,其中item_names的值看起来像“abracadabra_prefix.tag_name”。 And I need to select rows with tag_names from a list that doesn't have a prefix.
我需要从没有前缀的列表中提取 select 行带有 tag_names 的行。
Should be somthing like:应该是这样的:
tag_names = ['f1', 'k500', '23_g']
SELECT * FROM table WHERE item_name IN (LIKE "%{tag_names});
input table:输入表:
item_name![]() |
value![]() |
---|---|
fasdaf.f1![]() |
1 ![]() |
asdfe.f2 ![]() |
2 ![]() |
eywvs.24_g ![]() |
2 ![]() |
asdfe.l500 ![]() |
2 ![]() |
asdfe.k500 ![]() |
2 ![]() |
eywvs.23_g ![]() |
2 ![]() |
output table: output表:
item_name![]() |
value![]() |
---|---|
fasdaf.f1![]() |
1 ![]() |
asdfe.k500 ![]() |
2 ![]() |
eywvs.23_g ![]() |
2 ![]() |
I have tried concatenating a string in a loop to get a query like this:我试过在循环中连接一个字符串来获得这样的查询:
SELECT * FROM table WHERE item_name LIKE '%f1' OR item_name LIKE '%k500' OR item_name LIKE '%23_g';
But I can have from 1 to 200 tags, and with a large number of tags, this makes the query too complicated,as I understand it.但是我可以有 1 到 200 个标签,并且标签数量很多,这使得查询过于复杂,据我所知。
You can use:您可以使用:
UNNEST
to extract tag values from your array, UNNEST
从数组中提取标签值,CROSS JOIN
to associate tag value to each row of your table CROSS JOIN
将标签值关联到表的每一行LIKE
to make a comparison between your item_name and your tag LIKE
在你的 item_name 和你的标签之间进行比较SELECT item_name, value_
FROM tab
CROSS JOIN UNNEST(ARRAY['f1', 'k500', '23_g']) AS tag
WHERE item_name LIKE '%' || tag || '%'
Output: Output:
item_name![]() |
value_![]() |
---|---|
fasdaf.f1![]() |
1 ![]() |
asdfe.k500 ![]() |
2 ![]() |
eywvs.23_g ![]() |
2 ![]() |
You can extract the suffix of item_name
using substring
with regexp and then use the any
operator for comparison in the where
clause.您可以使用
substring
和正则表达式提取item_name
的后缀,然后在where
子句中使用any
运算符进行比较。
select * from the_table
where substring (item_name from '\.(\w+)$') = any('{f1,k500,23_g}'::text[]);
SQL fiddle demo SQL 小提琴演示
If you intend to use the query as a parameterized one then it will be convenient to replace '{f1,k500,23_g}'::text[]
with string_to_array('f1,k500,23_g', ',')
, ie pass the list of suffixes as a comma-separated string.如果您打算将查询用作参数化查询,那么将
'{f1,k500,23_g}'::text[]
替换为string_to_array('f1,k500,23_g', ',')
会很方便,即通过以逗号分隔的字符串形式的后缀列表。 Please note that this query will result in a sequential scan.请注意,此查询将导致顺序扫描。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.