将此MySQL查询转换为Codeigniter Active Record

时间:2014-08-16 22:33:32

标签: php mysql sql codeigniter

我有两张桌子:

Dress (dress_id, title)
Dress_comment (comment_id, dress_id, comment)

我已经尝试了几个小时,无法将此查询转换为相应的Codeigniters'活动类记录功能。

以下是查询:

SELECT d.dress_id, d.title, COALESCE(dc.count, 0) 
FROM dress d
JOIN (select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc 
ON d.dress_id = dc.dress_id 
ORDER BY d.dress_id;

这是我迄今为止所尝试过的:

    //Creating the select subquery for the inner join
    $this->db->select('dress_id, count(comment_id) as count')
                         ->from('Dress_comment')
                         ->group_by('dress_id')
                         ->get();
    $subQuery = $this->db->last_query();

    //Main Query 
    $this->db->select('d.dress_id, d.title, COALESCE(dc.count,0)')
             ->from('Dress')
             ->join($subQuery . ' dc','dc.dress_id = d.dress_id','left')
             ->order_by('d.dress_id');

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

    return $result->result_array();

但Codeigniter没有运行此查询并始终给出mysql语法错误。 codeigniter将此活动方法转换为的格式是

SELECT `d`.`dress_id`, `d`.`title`, COALESCE(dc.count, `0)` 
FROM (`Dress`) LEFT JOIN `SELECT`     `dress_id`, count(comment_id) as count 
FROM (`Dress_comment`) 
GROUP BY `dress_id` dc 
ON `dc`.`dress_id` = `d`.`dress_id` 
ORDER BY `d`.`dress_id`

1 个答案:

答案 0 :(得分:0)

我能够在join函数中使用mysql查询解决问题,如下所示:

        $this->db->select('d.dress_id, d.title, dc.count as comments, dl.count as likes, dt.title, di.image_url')
             ->from('Dress d')
             ->join('(select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc','dc.dress_id = d.dress_id','left')
             ->order_by('d.dress_id');