title: Distinct & Group SQL Query
body: <p>I have a little bit complex MySQL query for me and i can't figure out how to write it without eating tons of memory. ( i don't really mind if it would )</p>
  
  <p>I have the following table:</p>
  
  <pre><code>              TABLE: users(id,ip)
                ------------------------------------
                4BF1510 | 40.145.10.99 &lt;-- SAME IP (A)
  SAME ID   --&gt; 510SD55 | 65.12.105.42 
  SAME ID   --&gt; 510SD55 | 45.184.15.10
                201505V | 40.145.10.99 &lt;-- SAME IP (A)
                984AZ6C | 72.98.45.76
                        | 10.15.78.10  &lt;-- SAME IP (B)
                        | 10.15.78.10  &lt;-- SAME IP (B)
  SAME ID   --&gt; B1D56SX |  
  SAME ID   --&gt; B1D56SX |  
  </code></pre>
  
  <p>I want a query that only fetchs 1 item per a unique id or ip, So:</p>
  
  <pre><code>4BF1510 | 40.145.10.99
  510SD55 | 65.12.105.42
  984AZ6C | 72.98.45.76
          | 10.15.78.10
  B1D56SX |
  </code></pre>
  
  <p>The Most important things:</p>
  
  <ul>
  <li>If multiple entries have the same IP and same ID -> they'll be grouped</li>
  <li>If multiple entries have the same IP but different IDs -> they'll not be grouped</li>
  <li>If multiple entries have the same ID but different IPs -> they'll be grouped</li>
  <li>If multiple entries have the same IP but <em>empty</em> ID fields -> they'll be grouped</li>
  <li>If multiple entries have the same ID but <em>empty</em> IP fields -> they'll be grouped</li>
  </ul>
  
  <p>Which means that the ID should have the first priority of trust, Because multiple users may use the same IP.</p>
  
  <p>Any effective way to achieve that?</p>
  
  <p>Tons of thanks.</p>