如何指定WHERE子句,以便在列的值(字符串列表)与另一个字符串列表之间存在交集时返回一行? 类似的东西:
SELECT id, names
FROM table
WHERE ANY(names) = ANY(('John', 'Alice', 'Bob'))
因此,如果值names
列是,例如['George', 'Bob']
,应返回该行。
答案 0 :(得分:3)
You should really use arrays or a table of records for this
您可以splitting strings into arrays at runtime和using PostgreSQL's array features处理您的设计。
SELECT id, names
FROM table
WHERE string_to_array(names, ',') && ARRAY['John', 'Alice', 'Bob'];
如果您的逗号分隔值包含空格等,则可能需要regexp_split_to_array
而不是string_to_array
。
答案 1 :(得分:3)
如果你真的无法改变你的设计(正如Craig Ringer所提到的那样我会推荐)
您可以使用regexp_split_to_array
SELECT id, names
from (
SELECT
id,
names,
regexp_split_to_table(names, ', ') as splitted_value
from <yourTable>) t
where splitted_value in ('John', 'Alice', 'Bob')
group by id, names;
或更复杂,包含样本
SELECT id, names
from (
SELECT
id,
names,
regexp_split_to_table(replace(replace(names, '[''', ''), ''']', ''), ''', ''') as splitted_value
from <yourTable>) t
where splitted_value in ('John', 'Alice', 'Bob')
group by id, names;
另一种丑陋的方式,使用一些json函数(因为你的列数据看起来像json)
&#34;详细信息&#34; :我不是postgresql专家,也不是json数据部分的全部。所以可能有更好的方法来做到这一点。
select id, names
from
(select
id,
names,
replace(cast(json_array_elements(cast(replace(names, '''', '"') as json)) as text), '"', '') as elem
from <yourTable>) t
where elem in ('George', 'Bob');
答案 2 :(得分:0)
您可以生成自己的函数,它将模仿MYSQL的FIND_IN_SET
CREATE OR REPLACE FUNCTION find_in_set(str text, strlist text)
RETURNS int AS $$
SELECT i
FROM generate_subscripts(string_to_array($2,','),1) g(i)
WHERE (string_to_array($2, ','))[i] = $1
UNION ALL
SELECT 0
LIMIT 1
$$ LANGUAGE sql STRICT;
http://okbob.blogspot.ro/2009/08/mysql-functions-for-postgresql.html