2

嗨,我有来自上一个问题的以下查询,需要将其转换为 Doctrine 1.2 的 DQL。然而事实证明,DQL 不支持连接中的子查询。

SELECT * FROM contact c
  LEFT JOIN
    (SELECT a1.contact_id, a1.date, a1.activity_type_id FROM activity a1
      JOIN (SELECT contact_id, MAX(DATE) DATE FROM activity GROUP BY contact_id) a2
        ON a1.contact_id = a2.contact_id AND a1.date = a2.date
     ) a
  ON c.id = a.contact_id  

WHERE a.activity_type_id = 2;

我试图弄清楚如何在不诉诸多个查询的情况下以另一种方式做到这一点。

谢谢。

4

2 回答 2

3

使用原则,您不应该使用原始 sql 将子查询嵌套到 where 条件中。在更复杂的场景中你会遇到麻烦。而是使用createSubquery显式告知子查询的教义,让教义将其编译为 DQL,然后将其嵌套到您的 where 条件中。所以你的查询应该是这样的:

$q->from('Contact c') 
  ->leftJoin('c.Activity a')
;

$subquery = $q->createSubquery()
    ->select("a1.contact_id, MAX(a1.date) a1.date")
    ->from("Activity a1")
    ->groupby("a1.contact_id")
;

$q->where('ROW (c.id, date) IN ('.$subquery->getDql().')')
  ->andWhere('a.activity_type_id = ?', $filterActivityTypeId)
;

另一个例子可以在这里找到:

https://www.philipphoffmann.de/2012/08/29/a-bulletproof-pattern-for-creating-doctrine-subqueries-of-any-complexity/

于 2012-09-01T06:57:01.333 回答
2

最终查询:

SELECT * FROM contact c
    LEFT JOIN activity ON c.id = contact_id
    WHERE ROW (c.id,DATE) IN (SELECT contact_id, MAX(date) date FROM activity  GROUP BY contact_id)
    AND activity_type_id = 2

最终 DQL:

$q->from('Contact c') 
->leftJoin('c.Activity a')      
->where('ROW (c.id, date) IN (SELECT a1.contact_id, MAX(a1.date) a1.date FROM Activity a1 GROUP BY a1.contact_id)')
->andWhere('a.activity_type_id = ?', $filterActivityTypeId);
于 2012-08-10T13:34:24.810 回答