How to write Subquery in the active codeigniter entry for this query

 SELECT  from_id, (SELECT COUNT(id) FROM user_messages WHERE from_id=1223 AND status=1) AS sent_unread, 
    (SELECT COUNT(id) FROM user_messages WHERE from_id=1223 AND status=2) AS sent_read 
    FROM user_messages 
    WHERE from_id=1223 
    GROUP BY from_id

How to write the above select statement in an active CodeIgniter record?

Here is what I came up with:

  $this->db->select('from_id, (SELECT COUNT(id) FROM user_messages WHERE from_id=1223 AND status=1) AS sent_unread,
        (SELECT COUNT(id) FROM user_messages WHERE from_id=1223 AND status=2) AS sent_read');

    $this->db->where('from_id', $member_id);

    $this->db->group_by('from_id');

    $this->db->from('user_messages');

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

    //echo $this->db->last_query();
    return $result->row();

Is this the correct method?

+4
source share
1 answer

try it

<?php
      $query="from_id, (SELECT COUNT(id) FROM user_messages WHERE from_id=1223 AND status=1) AS sent_unread,
            (SELECT COUNT(id) FROM user_messages WHERE from_id=1223 AND status=2) AS sent_read";
      $query_run=$this->db->select($query);
      $query_run->where('from_id', $member_id);
      $query_run->group_by('from_id');

      $result = $query_run->get('user_messages');
      //echo $this->db->last_query();
       return $result->row();
    ?>
+5
source

Source: https://habr.com/ru/post/1611071/


All Articles