title: Rails: Performance issue with joining of records
body: <p>I have the following setup with ActiveRecord and MySQL:</p>
  <ol>
  <li><strong>User</strong> has many <code>groups</code> through memberships</li>
  <li><strong>Group</strong> has many <code>users</code> through memberships</li>
  </ol>
  <p>There is also an index by group_id and user_id described in schema.rb:</p>
  <pre><code>add_index &quot;memberships&quot;, [&quot;group_id&quot;, &quot;user_id&quot;], name: &quot;uugj_index&quot;, using: :btree
  </code></pre>
  <h3>3 different queries:</h3>
  <pre><code>User.where(id: Membership.uniq.pluck(:user_id))
  </code></pre>
  <blockquote>
  <p>(3.8ms)  SELECT DISTINCT <code>memberships</code>.<code>user_id</code> FROM <code>memberships</code>
  User Load (11.0ms)  SELECT <code>users</code>.* FROM <code>users</code> WHERE <code>users</code>.<code>id</code> IN (1, 2...)</p>
  </blockquote>
  <pre><code>User.where(id: Membership.uniq.select(:user_id))
  </code></pre>
  <blockquote>
  <p>User Load (15.2ms)  SELECT <code>users</code>.* FROM <code>users</code> WHERE <code>users</code>.<code>id</code> IN (SELECT DISTINCT <code>memberships</code>.<code>user_id</code> FROM <code>memberships</code>)</p>
  </blockquote>
  <pre><code>User.uniq.joins(:memberships)
  </code></pre>
  <blockquote>
  <p>User Load (135.1ms)  SELECT DISTINCT <code>users</code>.* FROM <code>users</code> INNER JOIN <code>memberships</code> ON <code>memberships</code>.<code>user_id</code> = <code>users</code>.<code>id</code></p>
  </blockquote>
  <p>What is the best approach for doing this? Why the query with join is much slower?</p>