title: Order by within group by in Doctrine 2
body: <p>I'm using Symfony 2 PR12 with Doctrine 2 and MySQL. I have a database storing articles and views of those articles:</p>
  
  <pre><code>// ...
  class Article {
  
      /**
       * @orm:Column(type="bigint")
       * @orm:Id
       * @orm:GeneratedValue
       * @var int
       */
      protected $id;
  
      /**
       * @orm:OneToMany(targetEntity="ArticleView",mappedBy="article")
       * @var ArrayCollection
       */
      protected $views;
  
      // ...
  }
  
  // ...
  class ArticleView {
  
      /**
       * @orm:Column(type="bigint")
       * @orm:Id
       * @orm:GeneratedValue
       * @var int
       */
      protected $id;
  
      /**
       * @orm:Column(type="bigint",name="DateRead",nullable=true)
       * @var int
       */
      protected $viewDate;
  
      /**
       * @orm:ManyToOne(targetEntity="Article",inversedBy="views")
       * @var Article
       */
      protected $article;
  
      // ...
  }
  </code></pre>
  
  <p>I want to get, for example, the 20 most-recently-viewed articles.  My first thought would be something like:</p>
  
  <pre><code>$qb = &lt;instance of Doctrine\ORM\QueryBuilder&gt;;
  $qb-&gt;select('a')
     -&gt;from('Article', 'a')
     -&gt;join('a.views', 'v')
     -&gt;orderBy('v.viewDate', 'DESC')
     -&gt;groupBy('a.id')
     -&gt;setMaxResults(20)
  ;
  </code></pre>
  
  <p>However, when there's more than one view associated with an article, the order-by/group-by combination gives unpredictable results for the ordering.</p>
  
  <p>This is expected behavior for MySQL, since grouping is handled before ordering, and there are working raw-query solutions to this problem at <a href="http://www.artfulsoftware.com/infotree/mysqlquerytree.php" rel="noreferrer">http://www.artfulsoftware.com/infotree/mysqlquerytree.php</a> (Aggregates -> Within-group aggregates).  But I can't figure out how to translate any of these solutions into DQL, since as far as I can tell there's no way to select from subqueries or perform self-exclusion joins.</p>
  
  <p>Any ideas on how to solve the problem with reasonable performance?</p>