Search code examples
mysqlcodeigniter-3

Get Total View from three different tables


Hello Everyone I am a Codeigniter Beginner,

In controller I am sending data like-

1

$send['rowa'] = $this->db->query("
SELECT sum(views) as rowCount 
  from table_a
")->result();

2

$send['rowb'] = $this->db->query("
SELECT sum(view_counter) as rowCount 
  from table_b
")->result();

3

$send['rowc'] = $this->db->query("
SELECT sum(view_counter) as rowCount 
  from table_c
")->result();

In view I am using

'<=$rowa[0]->rowCount;?>, <=$rowb[0]->rowCount;?>, <=$rowc[0]->rowCount;?>.

I am getting the actual output like

12, 34, 21.

I want to get the total of

12+34+21= 67.

How I can get it?

Thank you all


Solution

  • you can use

    $send['total'] = $this->db->query("SELECT (SELECT sum(views) as rowCount from table_a)+(SELECT sum(view_counter) as rowCount from table_b)+(SELECT sum(view_counter) as rowCount from table_c) as rowCount;")->result();
    

    Which will run

    SELECT 
    (SELECT sum(views) as rowCount from table_a) 
    +(SELECT sum(view_counter) as rowCount from table_b)
    +(SELECT sum(view_counter) as rowCount from table_c) as rowCount;
    

    As every select only returns 1 result this can be used to add the results