教义QueryBuilder from with子查询

时间:2018-10-11 12:25:58

标签: php mysql doctrine query-builder

我需要编写一些复杂的查询生成器表达式。 sql看起来像:

SELECT query,popularity,nb_words
FROM gemini_suggestion    
WHERE query IN    
(
    SELECT * FROM    
    (   
        SELECT query    
        FROM gemini_suggestion    
        GROUP BY query    
        HAVING COUNT(query) > 1    
    ) AS subquery    
);

我停留在的代码是:

$queryBuilder = $em->createQueryBuilder();
$queryBuilder->select('a')
    ->from($this->entity['class'], 'a')
    ->where($queryBuilder->expr()->In('a.query', $subQuery->getDQL()));

$subQuery2 = $em->createQueryBuilder()
    ->select('b.query')
    ->from($this->entity['class'], 'b')
    ->groupBy('b.query')
    ->having('count(b.query)>1')
;

$subQuery = $em->createQueryBuilder();
$subQuery->select('a')
    ->from(...)
;

任何帮助都会很好!

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的方法。我假设您有一个具有所有实体类的名称空间Entities。

// Subquery to get the queries greater than 1
$subQueryBuilder = $this->entityManager->createQueryBuilder();
$subQueryBuilder->select('gemini_suggestion.query')
                ->from('Entities\gemini_suggestion', 'gemini_suggestion')
                ->groupBy('gemini_suggestion.query')
                ->having($subQueryBuilder->expr()->gt('COUNT(gemini_suggestion.query)', 1));

// Main query where you use the subquery to filter out the records you want
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('query, popularity, nb_words')
             ->from('Entities\gemini_suggestion', 'gemini_suggestion')
             ->where($queryBuilder->expr()->in('gemini_suggestion.query', $subQueryBuilder->getDQL()));

$result = $queryBuilder->getQuery()->getResult();
return $result;