2

我正在尝试通过学说运行以下查询:

$sql = "SELECT league_id, sum(num_fans) AS total_fans FROM ("
."SELECT COUNT(*) as num_fans, t.id AS team_id, l.id AS league_id FROM fan_link fl "
."JOIN team t ON fl.team_id = t.id JOIN League l ON t.league_id = l.id GROUP BY fl.team_id"
.") a GROUP BY league_id LIMIT 0, 3";

$results = $this->em->createQuery($sql)->getScalarResult();

该查询在 PHPMyAdmin 中运行良好,但是当我尝试在学说中运行它时,我收到此错误:

Doctrine\ORM\Query\QueryException [ 0 ]: 
[Semantical Error] line 0, col 51 near '(SELECT COUNT(*)': 
Error: Class '(' is not defined.

括号(是教义查询中的保留字符吗?我在where其他地方的子句中有子选择可以正常工作,但是子句中的这个from子句不想工作。我究竟做错了什么?

更新:
我刚刚尝试使用查询生成器并得到了同样的错误。代码:

$qb = $this->em->createQueryBuilder();
$leagueQuery = $qb->select('league_id, sum(num_fans) AS total_fans')
    ->from("(SELECT count(*) as num_fans, t.id AS team_id, l.id AS league_id "
    ."FROM fan_link fl "
    ."JOIN team t ON fl.team_id = t.id "
    ."JOIN League l ON t.league_id = l.id GROUP BY fl.team_id)",
    'a')
    ->groupBy("league_id")
    ->orderBy("total_fans", "DESC")
    ->setMaxResults(3)
    ->getQuery();

$results = $leagueQuery->getArrayResult();
4

2 回答 2

0

最终使用了这个:

$sql = "SELECT league_id, sum(num_fans) AS total_fans FROM "
    ."(SELECT COUNT(*) as num_fans, t.id AS team_id, l.id AS league_id FROM fan_link fl "
    ."JOIN team t ON fl.team_id = t.id JOIN League l ON t.league_id = l.id GROUP BY fl.team_id"
    .") a GROUP BY league_id LIMIT 0, 3";
$q = $this->em->getConnection();
$league_results = $q->fetchAll($sql);
于 2012-09-23T18:33:37.110 回答
0

花很多时间来完成这项工作!

你可以用createNativeQuery()

这是工作示例:

$rsm = new ResultSetMapping();
$rsm->addScalarResult('c1', 'c1');
$rsm->addScalarResult('b1', 'b1');

$qb = $manager->createNativeQuery("
SELECT SUM(RESULTS.totalHours) AS c1, SUM(RESULTS.totalDuration) AS b1
FROM
(
    SELECT S.totalHours, S.totalDuration
    FROM S
    INNER JOIN SV ON S.specificationId = SV.id
    LEFT JOIN SToTagRel ST ON S.id = ST.specificationId
    LEFT JOIN T ON ST.tagId = T.id
    GROUP BY S.id
) AS RESULTS
", $rsm);

$qb->getSingleResult();

于 2016-12-14T16:13:34.720 回答