php - codeigniter,如何获取多个查询并从模型中对其进行计数

标签 php mysql codeigniter

我是 Codeigniter 的新手。我正在尝试让我的模型返回两个查询,一个是针对数据本身(表中的一些注释),另一个是计算字段。并返回表单的输出(非常好、好和坏)。在他与 officer_name 相关的投票中。问题是当我从三个不同的查询中使用 count(*) 时,结果仅为空。

这是来 self 的模型的查询。

$this->db->select('a.id_poll')
                ->select('a.poll')
                ->select('a.date')
                ->select('a.id_officer')
                ->select('b.officer_name')
                ->select('c.id_service')
                ->select('c.service_name')
                ->select('count(a.poll) as verygood')
                ->where('b.officer_name', $officer['officer_name'])
                ->where('a.poll','verygood')
                ->select('count(a.poll) as good')
                ->where('b.officer_name', $officer['officer_name'])
                ->where('a.poll','good');
                ->select('count(a.poll) as bad')
                ->where('b.officer_name', $officer['officer_name'])
                ->where('a.poll','bad');
$this->db->from('tbl_poll as a');
$this->db->join('tbl_officer as b', 'a.id_officer = b.id_officer');
$this->db->join('tbl_service as c', 'b.id_service = c.id_service');
return $this->db->get()->result_array();

这是我想要的输出:

Officer_name | Service |        Polls          |
             |         | Verygood | Good | Bad |
Bella        | Payments|    3     |  2   |  1  |
Christy      |   CS    |    5     |  3   |  0  |
ETC.         |   etc   |    3     |  3   |  3  |

有人可以帮助我以及如何做到这一点,或者修复我当前的代码吗?

提前致谢!

抱歉我的英语太差了

这是 sqlfiddle

最佳答案

试试这个,可能会有帮助。

$this->db->select('a.id_poll,a.poll,a.date,a.id_officer,b.officer_name,c.id_service,c.service_name,count(a.poll) as verygood,count(a.poll) as good,count(a.poll) as bad');
$this->db->from('tbl_poll as a');

$this->db->join('tbl_officer as b', 'a.id_officer = b.id_officer');
$this->db->join('tbl_service as c', 'b.id_service = c.id_service');

$this->db->where('b.officer_name', $officer['officer_name'])
$this->db->where('a.poll','verygood')

$this->db->where('b.officer_name', $officer['officer_name'])
$this->db->where('a.poll','good');

$this->db->where('b.officer_name', $officer['officer_name'])
$this->db->where('a.poll','bad');

$query = $this->db->get();

$result = $query->result_array();

//To check the resutl for test purpose only

echo "<pre>";  print_r($this->db->last_query()); echo "</pre>";  // To check the query
echo "<pre>";  print_r($result); echo "</pre>";

关于php - codeigniter,如何获取多个查询并从模型中对其进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46638339/

相关文章:

mysql - 我应该如何存储类似的实体 - 在一个表或多个表中?

php - 分组和排序问题

php - 如何使用 codeigniter 在同一字段中搜索 2 个值?

php - 从 jQuery .ajax() 在 PHP 中获取 JSON

php - php exec() 中的 sudo

php - 如何通过选择或复选框插入多行

php - mysql_fetch_array,似乎没有返回值

php - 将 CURL 响应存储在 MySQL 数据库中会导致列开头出现问号

php - 异步保存数据php

php 时间戳转 javascript 时间或日期