title: Can I merge two MySQL queries into one?
body: <p>I had the following code, which uses 2 queries to get the friends list.</p>
  <pre><code>&lt;?php
  
  $getFriendStatement = &lt;&lt;&lt;EOS
    SELECT DISTINCT u.username
      FROM users AS u 
        INNER JOIN test_friends AS f on u.Id = f.user_id 
      WHERE f.friend_id = ?
         &amp;&amp; f.active=1
  EOS;
  
  $getFriendQuery = $mysqli-&gt;prepare($getFriendStatement);
  $getFriendQuery-&gt;bind_param('i', $userID);
  $getFriendQuery-&gt;execute() or die ($mysqli-&gt;error);
  $getFriendResult = $getFriendQuery-&gt;get_result();
  
  $friendName = &quot;&quot;;
  
  while ($getFriendFetch = $getFriendResult-&gt;fetch_assoc()) {
    $friendName .= $getFriendFetch['username'] . &quot;, &quot;;
  }
  
  
  $getFriendStatement = &lt;&lt;&lt;EOS
      SELECT u.username 
        FROM users AS u 
          INNER JOIN test_friends AS f ON u.id = f.user_id 
        WHERE (f.friend_id = ? AND active=1) 
           OR (f.user_id = ? AND active=1)
  EOS;
  
  $getFriendQuery = $mysqli-&gt;prepare($getFriendStatement);
  $getFriendQuery-&gt;bind_param('ii', $userID, $userID);
  $getFriendQuery-&gt;execute() or die ($mysqli-&gt;error);
  $getFriendResult = $getFriendQuery-&gt;get_result();
  
  
  while ($getFriendFetch = $getFriendResult-&gt;fetch_assoc()) {
    $friendName .= $getFriendFetch['username'] . &quot;, &quot;;
  }
                          
  
  if (!empty($friendName)){
    echo &quot;Your friends: &quot; . $friendName ;
  } else {
    echo &quot;You do not have any friends yet&quot;;
  }   
  
  ?&gt;
  </code></pre>
  <p>Is there a way to execute just 1 query to retrieve all friends?</p>
  <p>Schema information: the above relies on two tables, <code>users</code> and <code>test_friends</code>:</p>
  <pre><code>CREATE TABLE users (
    `id` int(11),
    `username` varchar(256)
  );
  
  CREATE TABLE test_friends (
    `user_id` int(11),
    `friend_id` int(11),
    `active` tinyint,
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
      ON UPDATE CASCADE ON DELETE CASCADE,
    FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`)
      ON UPDATE CASCADE ON DELETE CASCADE
  );
  </code></pre>