PostgreSQL where all in array

后端 未结 9 1574
情书的邮戳
情书的邮戳 2020-11-30 07:23

What is the easiest and fastest way to achieve a clause where all elements in an array must be matched - not only one when using IN? After all it should behave

9条回答
  •  Happy的楠姐
    2020-11-30 08:02

    I'm collapsing those users into an array. I'm also using a CTE (the thing in the WITH clause) to make this more readable.

    => select * from conversations_users ;
     conversation_id | user_id
    -----------------+---------
                   1 |       1
                   1 |       2
                   2 |       1
                   2 |       3
                   3 |       1
                   3 |       2
    (6 rows)       
    
    => WITH users_on_conversation AS (
      SELECT conversation_id, array_agg(user_id) as users
      FROM conversations_users
      WHERE user_id in (1, 2) --filter here for performance                                                                                      
      GROUP BY conversation_id
    )
    SELECT * FROM users_on_conversation
    WHERE users @> array[1, 2];
     conversation_id | users
    -----------------+-------
                   1 | {1,2}
                   3 | {1,2}
    (2 rows) 
    

    EDIT (Some resources)

    • array functions: http://www.postgresql.org/docs/9.1/static/functions-array.html
    • CTEs: http://www.postgresql.org/docs/9.1/static/queries-with.html

提交回复
热议问题