title: postgres - finding unique users which have specific records
body: <p>I need some help completing the following query with postgres.</p>
  
  <p>I have the following table for example: (this is the essence of what im trying to accomplish)</p>
  
  <p>lets call it - table_user_flags</p>
  
  <pre><code>user_id flag
  1        1
  1        2
  2        1
  2        3
  3        1
  3        2
  3        3
  </code></pre>
  
  <p>I need to find all users which have records with specific flags (under flag column, at least 1 record with each flag)</p>
  
  <p>Example:
  all users which have records with flags 1,3 (i.e 1 and 3) answer (user_id 2,3)
  (but also would like to make it simple to extend so that i can request flags 1,2,3,4,5 etc)</p>
  
  <p>I tried many things, unfortunately I was not able to articulate the situation well enough to find an answer on google.</p>
  
  <p>My best guess (which is lame and possibly faulty) is (and provided flags array - $flag_arr)</p>
  
  <pre><code>select a.user_id
  from table_user_flags a, table_user_flags b
  where a.flag = $flag_arr[0] and b.flag = $flag_arr[1] and a.user_id=b.user_id
  </code></pre>
  
  <p>but this strategy is slow, and also will only work if i need 2 flags, when i need more than 2 flags I will need to write specific queries for each length of the flags_arr.</p>
  
  <p>How can I solve this?</p>
  
  <p>I will appreciate any help!</p>