你好,我有这个问题
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 格式时遇到问题,我不知道该怎么做,请帮忙
最佳答案
你可以这样做
$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
$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();
关于php - 将查询转换为 codeigniter 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627485/