【问题标题】:How to count number of rows while using UNION in codeigniter?在codeigniter中使用UNION时如何计算行数?
【发布时间】:2019-06-07 01:18:40
【问题描述】:
$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。那么,我该怎么做呢?请帮帮我。

谢谢

【问题讨论】:

    标签: php codeigniter mysqli


    【解决方案1】:

    如果您的查询没问题,并且每个查询都返回您需要的确切结果,现在您只想获取行数,那么最好使用count_all_results() .. 并且为了安全起见并在之前重置查询生成器进行另一个查询:

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

    如果您的查询正常,它们都应该返回结果计数,然后简单地添加它们:

    $sum = $r1 + $r2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2021-05-07
      • 2011-09-27
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多