Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
列表列的SQL WHERE子句_Sql_Postgresql - Fatal编程技术网

列表列的SQL WHERE子句

列表列的SQL WHERE子句,sql,postgresql,Sql,Postgresql,如何指定WHERE子句,以便在列的字符串值列表与提供的另一个字符串列表相交时返回一行? 比如: SELECT id, names FROM table WHERE ANY(names) = ANY(('John', 'Alice', 'Bob')) 因此,如果value names列为,例如,['George','Bob',],则应返回该行。您可以生成自己的函数,该函数将模拟MYSQL的FIND_IN_SET CREATE OR REPLACE FUNCTION find_in_set(str

如何指定WHERE子句,以便在列的字符串值列表与提供的另一个字符串列表相交时返回一行? 比如:

SELECT id, names
FROM table
WHERE ANY(names) = ANY(('John', 'Alice', 'Bob'))

因此,如果value names列为,例如,['George','Bob',],则应返回该行。

您可以生成自己的函数,该函数将模拟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;

您可以通过和围绕您的设计工作


如果逗号分隔的值有空格等,您可能希望使用regexp\u split\u to\u数组,而不是string\u to\u数组。

如果您确实无法更改我建议的设计,就像Craig Ringer提到的那样

您可以使用regexp\u split\u to\u数组

 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

细节:我不是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');

列中以逗号分隔的字符串列表通常被认为是设计缺陷。@RaphaëlAlthaus是的,它几乎总是设计缺陷。看,把它变成一个可分析的字符串会更好吗?@CraigRinger通常几乎总是这样;只是一个疑问:名称的数据类型是什么?可能是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');