在Codeigniter中使用UNION时如何计算行数?

时间:2019-01-12 08:48:09

标签: php codeigniter mysqli

$this->db->select('*');
$this->db->from('table1');
$where = "tag = '".$tag."'";
$this->db->where($where);
$query1 = $this->db->get();
$result1 = $query1->num_rows();

$this->db->select('*');
$this->db->from('table2');
$where = "tag = '".$tag."'";
$this->db->where($where);
$query2 = $this->db->get();
$result2 = $query2->num_rows();

$result = $result1+$result2;
return $result;

在这个问题中,我有两个表table1 and table2,其中两个表的结构都相同。现在,我要计算行数。现在,它向我显示了错误的计数数据。如果第一个表中存在tag个数据,则它计数为1,如果两个表中都有tag个数据,则计数为2。那么,我该怎么做?请帮助我。

谢谢

1 个答案:

答案 0 :(得分:0)

如果您的查询正常,并且每个查询都返回您需要的确切结果,那么现在您只想获取行数,那么最好使用count_all_results() ..并保证安全并重置查询生成另一个查询之前构建器:

...
$r1= $this->db->count_all_results();
$this->db->reset_query();
...
$r2= $this->db->count_all_results();

如果您的查询没问题,则它们两者都应返回结果计数,然后只需将它们添加:

$sum = $r1 + $r2;