如何在此查询的 codeigniter 活动记录中编写子查询
Posted
技术标签:
【中文标题】如何在此查询的 codeigniter 活动记录中编写子查询【英文标题】:How to write Subquery in codeigniter active record for this query 【发布时间】:2016-01-08 05:51:05 【问题描述】: 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
如何在CodeIgniter活动记录中编写上述select语句?
这是我想出的:
$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();
这是正确的方法吗?
【问题讨论】:
【参考方案1】:试试这个
<?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();
?>
【讨论】:
如果我们有两个查询怎么办? @daular以上是关于如何在此查询的 codeigniter 活动记录中编写子查询的主要内容,如果未能解决你的问题,请参考以下文章
如何在codeigniter活动记录中使用select插入记录