Codeigniter - 将mysql查询转换为CodeIgniter的活动记录查询

时间:2012-09-07 16:59:52

标签: mysql codeigniter subquery

我正在尝试将此SQL查询转换为codeigniter查询

SELECT 
  uploads.EMAIL
FROM
  uploads 
  JOIN (

    SELECT EMAIL, COUNT(*) as num FROM uploads GROUP BY EMAIL
  ) c ON uploads.EMAIL = c.EMAIL
ORDER BY 
  c.num DESC, 
  EMAIL ASC

感谢您的帮助 亲切的问候

1 个答案:

答案 0 :(得分:2)

我不确定为什么你不能使用active record documentation来解决这个问题,但是:

$this->db->select('uploads.EMAIL');
$this->db->from('uploads');
$this->db->join('(SELECT EMAIL, COUNT(*) as num FROM uploads GROUP BY EMAIL) c','uploads.EMAIL = c.EMAIL','',FALSE);
$this->db->order_by('c.num desc, uploads.EMAIL asc');

然后

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

FYI,将FALSE作为第四个参数传递给db->join()方法将导致它不会转义语句,所以如果你要采用外部变量,你应该小心。直到CodeIgniter 3,这是使用活动记录进行子查询而不扩展活动记录类以添加它们的唯一方法。