Postgresql Select rows where column = array

后端 未结 4 1858
闹比i
闹比i 2020-12-12 17:37

This is a summary of what I am trying to do:

$array[0] = 1;
$array[1] = 2;

$sql = \"SELECT * FROM table WHERE some_id = $array\"

Obviously

相关标签:
4条回答
  • 2020-12-12 18:18
    SELECT  *
    FROM    table
    WHERE   some_id = ANY(ARRAY[1, 2])
    

    or ANSI-compatible:

    SELECT  *
    FROM    table
    WHERE   some_id IN (1, 2)
    

    The ANY syntax is preferred because the array as a whole can be passed in a bound variable:

    SELECT  *
    FROM    table
    WHERE   some_id = ANY(?::INT[])
    

    You would need to pass a string representation of the array: {1,2}

    0 讨论(0)
  • 2020-12-12 18:21

    For dynamic SQL use:

    'IN(' ||array_to_string(some_array, ',')||')'

    Example

    DO LANGUAGE PLPGSQL $$
    
    DECLARE
        some_array bigint[];
        sql_statement text;
    
    BEGIN
    
        SELECT array[1, 2] INTO some_array;
        RAISE NOTICE '%', some_array;
    
        sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
        RAISE NOTICE '%', sql_statement;
    
    END;
    
    $$;
    

    Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

    0 讨论(0)
  • 2020-12-12 18:31
       $array[0] = 1;
       $array[2] = 2;
       $arrayTxt = implode( ',', $array);
       $sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"
    
    0 讨论(0)
  • 2020-12-12 18:33

    In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

    SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])
    

    I spent almost 6 hours before I stumble on the post.

    0 讨论(0)
提交回复
热议问题