我想对四个表执行查询。
User
Employments
Company
Votes
User
并Company
通过Employments
. Votes
与其他三个实体没有直接关系(例如通过 PK 和 FK)。但Votes
间接相关Company
,因为它包含一个列company
,该name
列具有与Company
我可以直接在本机 SQL 中管理查询,但在 Doctrine2 中我看不到任何灯。
本机 SQL 中的查询看起来与此有关
SELECT
c.name AS company,
AVG(vo.vote) AS value,
COUNT(vo.vote) AS votes,
em.employees AS employees
FROM company c
LEFT JOIN employment e ON c.id = e.company_id
LEFT JOIN user u ON e.user_id = u.id
LEFT JOIN (SELECT v.company, v.face
FROM vote v
WHERE v.gender IS NULL
AND v.age IS NULL
AND YEAR( v.timestamp ) = 2013
AND MONTH( v.timestamp ) = 09
AND DAY( v.timestamp ) = 26
) vo ON vo.company = c.name
LEFT JOIN (SELECT employment.company_id, COUNT(employment.user_id) AS employees FROM employment GROUP BY employment.company_id) em ON em.company_id = c.id
WHERE u.id = 1
GROUP BY c.name
如前所述:这在纯 SQL 中工作得很好而且很容易。所以我试图将它“翻译”成 DQL:
$subqueryVotes = "SELECT v.company, v.vote
FROM vote v
WHERE v.gender IS NULL
AND v.age IS NULL
AND YEAR( v.timestamp ) = :year
AND MONTH( v.timestamp ) = :month
AND DAY( v.timestamp ) = :day";
$subqueryEmployeecount = "SELECT employment.company_id, COUNT(employment.user_id) AS employees FROM employment GROUP BY employment.company_id";
$query = $em->createQuery(
'SELECT
c.name AS company,
AVG(vo.vote) AS value,
COUNT(vo.vote) AS votes,
em.employees AS employees
FROM MyBundle:Company c,
('.$subqueryVotes.') vo,
('.$subqueryEmployeecount.') em
LEFT JOIN c.employments e
LEFT JOIN e.employee u
WHERE vo.gender IS NULL
AND vo.age IS NULL
AND YEAR( vo.timestamp ) = :year
AND MONTH( vo.timestamp ) = :month
AND DAY( vo.timestamp ) = :day
AND u.id = :id
AND vo.company = c.name
AND em.company_id = c.id
GROUP BY c.name'
);
$query->setParameters(array(
'year' => $year,
'month' => $month,
'day' => $day,
'id' => $this->getUser()->getId()
));
$result = $query->getArrayResult();
但现在我得到:
[Semantical Error] line 0, col 149 near '(
SELECT': Error: Class '(' is not defined.
这是因为我的FROM
子句中有括号中的子选择。语句中的子查询是否FROM
不允许?如何更改我的查询才能正确执行?