将查询转换为codeigniter格式

时间:2014-03-25 07:01:03

标签: php mysql codeigniter

Hello guy我有这个查询

SELECT distinct blog.*,(select count(blog_id) from blog_comment where blog_comment.blog_id=blog.id) as comment FROM blog Left JOIN blog_comment ON blog.id = blog_comment.blog_id

我希望此查询采用CI格式。此查询的列中包含subquery 所以我面临的问题是将此查询转换为CI格式我不知道如何做到这一点请帮助

2 个答案:

答案 0 :(得分:3)

你可以这样做

$this->db->select('distinct blog.*,
(select count(blog_id) from blog_comment where blog_comment.blog_id=blog.id) as comment ',FALSE);
$this->db->from('blog')
$this->db->join('blog_comment','blog.id = blog_comment.blog_id','LEFT');
$this->db->get();

您可以在不使用子查询的情况下重写原始查询

SELECT DISTINCT 
  b.*,
  COUNT(bc.blog_id) `comment`
FROM
  blog b
  LEFT JOIN blog_comment  bc
  ON b.id = bc.blog_id 
  GROUP BY b.id

Active Record

$this->db->select('b.*, COUNT(bc.blog_id) `comment`',FALSE);
$this->db->from('blog b')
$this->db->join('blog_comment bc','b.id = bc.blog_id ','LEFT');
$this->db->group_by('b.id'); 
$this->db->get();

答案 1 :(得分:0)

您可以在$this->db->query()

中使用上述查询

Queries : CodeIgniter User Guide - EllisLab