php - 将查询转换为 codeigniter 格式

标签 php mysql codeigniter

你好,我有这个问题

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

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();

关于php - 将查询转换为 codeigniter 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627485/

相关文章:

php - 在模板中将代码与布局分开

php - 操作 '=' 的排序规则混合非法

php - 我需要什么才能获得合规的电子邮件 header

PHP/CSS格式

mysql - 可重复读mysql

php - 在 Laravel5 中使用 Eloquent 模型获取表值

php - 通过 Gmail SMTP 在 CodeIgniter 中发送电子邮件时遇到问题

css - bootstrap/ci 应用程序的媒体查询失败

php - strip 创建发票/收费发票

php - 从长网址获取帖子 ID (php)