计算并显示特定列结果的数量

时间:2013-08-17 15:53:23

标签: mysql codeigniter

我有下表

|id|city|job|
|12|New York|Truck driver|
|13|Chicago|Postman|
|14|New York|Postman|
|15|Las Vegas|Dealer|
|16|Las Vegas|Dealer|
|17|New York|Post Office|

我希望能够计算每个城市有多少工作,然后以DESC顺序返回最多工作的十个城市。如下所示

  • 纽约(3)
  • 拉斯维加斯(2)
  • 芝加哥(1)

我如何做到这一点?

我的代码看起来像这样

 $this->db->select('city');
 $this->db->select_sum('city', 'total');
 $this->db->group_by('city'); 
 $this->db->order_by('total', 'desc'); 
 $query = $this->db->get('job', 10);

foreach ($query->result() as $row) {
    $data[] = array(
        'total' => $row->total,
        'city' => $row->city
    );
}

return $data;

我从这个帖子中获取灵感:COUNT / GROUP BY with active record?

但似乎没有做对。

2 个答案:

答案 0 :(得分:0)

为什么不使用$this->db->query();?

$this->db->query('SELECT CITY, COUNT(CITY) AS TOTAL FROM JOB GROUP BY CITY ORDER BY TOTAL DESC LIMIT 10');

答案 1 :(得分:0)

在这里: -

$query = $this->db->query('SELECT city, COUNT(city) AS jobcount FROM `jobs` GROUP BY city ORDER BY jobcount DESC');

if ($query->num_rows() > 0)
    foreach ($query->result() as $row) 
        $data[] = array(
            'total' => $row->jobcount,
            'city'  => $row->city
        );

return $data;

别忘了将'jobs'与您的表名交换