2011-09-05 52 views
2

我有兩個表:計數教義

Name 
    id | name | city_id 
    1 | aaa | 1 
    2 | vvv | 2 
    3 | ddd | 2 
    4 | sss | 3 
    5 | dds | 1 

City: 
id | name 
1 | London 
2 | NY 
3 | Boston 

我怎樣才能獲得市和計數:

name_city | count 
London | 2 
NY  | 2 
Boston | 1 

在城市表:

$q = $this->createQuery('a') 
      ->leftJoin('a.Name n') 
      ->select('a.name_city as name_city, sum(n.city_id) as sum'); 

     return $q->execute(); 

但這是錯誤的。

回答

3

您應該使用count()而不是sum(),此外,您還需要一個group by

1

這篇文章是有點幫助,但我雖然我會爲任何想加入2個表和聚合計數的人添加更多的細節。

例如這篇文章(http://stackoverflow.com/questions/7837671/mysql-join-tables-and-count-instances),但在教條。

使用查詢上面的例子將是(學說2.0):

$q = $this->em->createQueryBuilder('a') 
      ->select('a.name_city as name_city, count(n.city_id) as sum'); 
      ->from('city','a') 
      ->leftJoin('a.Name n') 
      ->groupBy('n.id') 
      ->orderBy('sum') 

    $query = $qb->getQuery(); 
    echo $qb->getDql(); // if you want to see the dql created 
    $result = $query->getResult();