php - Doctrine 从子查询中选择

标签 php mysql doctrine

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

$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 中运行它时,我得到了这个错误:

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

括号 ( 是 Doctrine 查询中的保留字符吗?我在其他地方的 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();

最佳答案

最终使用了这个:

$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);

关于php - Doctrine 从子查询中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12554202/

相关文章:

javascript - 将 html 表单数据保存到文件

php - 如何获取表行的值并在 else if 语句中使用它

php - Doctrine 查询语言获取每组最大/最新行

php - Symfony:动态更改数据库

php - Zend Framework 1.11 与 Doctrine 2 集成

php - Symfony 2.3.5 fatal error : Class 'ResourceBundle' not found on Server

php - 我可以使用任何 Django 风格的 PHP 框架吗?

php - 使用变量对 MySQL 数据进行排序

php - pdo 驱动程序不支持 Linux 上的事务

sql - `active' 标志与否?