【问题标题】:SQL query joining different tables and countSQL查询加入不同的表和计数
【发布时间】:2016-02-14 14:13:29
【问题描述】:

我的 SQL 查询语法很弱,我需要使用 php symfony2 进行一次查询。

我有表公司。它有“城市”列。
我有表 CompanyCategory。它有“company_id”和“category_id”列。
我有表类别。它有“名称”列。

我需要获取所有可用城市的类别总数。

例子:

["Riga" => 156,
"Berlin" => 225]

我已经环顾了几个小时,但其他示例对我的帮助不够,因为我还无法理解如此复杂的查询。

我之前和现在都尝试过很多案例,每次都遇到不同的异常。

public function getCategoriesInCities() {
    return $this->getEntityManager()
        ->createQuery('SELECT c.city, count(*) as categorycount FROM AdminBundle:Company c INNER JOIN AdminBundle:CompanyCategory s')
        ->getArrayResult();
}


[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got end of string.

其他情况:

public function getCategoriesInCities() {
    return $asData = $this->getEntityManager()
        ->createQuery('SELECT c.city, count(*) as categorycount FROM AdminBundle:Company c INNER JOIN AdminBundle:CompanyCategory s ON(c.id = s.company_id) GROUP BY c.city')
        ->getArrayResult();
}


[Syntax Error] line 0, col 123: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'

其他情况:

public function getCategoriesInCities() {
    return $this->createQueryBuilder('c')
        ->select('c.city, COUNT(*) as categorycount')
        ->innerJoin('AdminBundle:CompanyCategory ON(c.id = cc.company_id)', 'cc')
        ->groupBy('c.city')
        ->getQuery()
        ->getArrayResult();
}

[Syntax Error] line 0, col 138: Error: Expected Literal, got 'BY'

等等..找不到解决办法。

【问题讨论】:

    标签: php mysql symfony


    【解决方案1】:

    这是一个简单的 JOIN 查询..

    SELECT t.city,count(*) as categoryCount
    FROM Company t
    INNER JOIN CompanyCategory s ON(t.id = s.company_ID)
    GROUP BY t.city
    

    您对这个网站并不陌生,所以在未来,至少尝试展示您自己所做的一些尝试和努力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 2016-01-24
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多