gpt4 book ai didi

php - SQL查询连接不同的表并计数

转载 作者:行者123 更新时间:2023-11-29 11:43:17 25 4
gpt4 key购买 nike

我对 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'

等等...不知道如何解决这个问题。

最佳答案

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

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

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

关于php - SQL查询连接不同的表并计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35392768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com