title: Mixing LEFT JOIN results MySQL Doctrine
body: <p>I have a doctrine based application where I want to select rows from two separate tables and order them by creation date. I'm (sort of) accomplishing it this way right now:</p>
  
  <pre><code>$query = $em-&gt;createQueryBuilder()
    -&gt;from('Embed', 'e')
    -&gt;select("e")
    -&gt;leftJoin("User", "u", "WITH", "e.uid=u.id")
    -&gt;leftJoin("Product", "p", "WITH", "e.pid=p.id")
    -&gt;where("u.image &gt; 0 OR p.image &gt; 0")
    -&gt;addOrderBy("u.timeCreated + p.timeCreated", "DESC")
    -&gt;setMaxResults(28)
    -&gt;getQuery();
  </code></pre>
  
  <p>I would like for product and user data to be mixed, ordered by creation date, but the ordering is incorrect. I've also tried using two addOrderBy statements, which orders users and products correctly but puts all the users first in the results, rather than mixing them.</p>
  
  <p>EDIT: Sir Rufo had the correct approach - here's the working code:</p>
  
  <pre><code>$query = $em-&gt;createQueryBuilder()
    -&gt;from('Embed', 'e')
    -&gt;select("e")
    -&gt;leftJoin("User", "u", "WITH", "e.uid=u.id")
    -&gt;leftJoin("Product", "p", "WITH", "e.pid=p.id")
    -&gt;addSelect('COALESCE( u.timeCreated, p.timeCreated ) as timeCreated')
    -&gt;where("u.image &gt; 0 OR p.image &gt; 0")
    -&gt;orderBy("timeCreated", "DESC")
    -&gt;setMaxResults(28)
    -&gt;getQuery();
  </code></pre>