简体   繁体   English

将此MySQL查询转换为Codeigniter活动记录

[英]Convert this MySQL Query to Codeigniter Active Record

I have got two tables : 我有两个桌子:

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

I have been trying from hours now and unable to convert this query into the corresponding Codeigniters' Active Class Record functions. 我已经尝试了几个小时,无法将此查询转换为相应的Codeigniters的Active Class Record函数。

Here is the query : 这是查询:

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;

This is what I have tried till now : 这是我到目前为止尝试过的:

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

But Codeigniter is not running this query and always giving mysql syntax error. 但是Codeigniter没有运行该查询,并且总是给出mysql语法错误。 The sql format that codeigniter is converting this active methods to is Codeigniter将此活动方法转换为的sql格式为

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`

I was able to solve the problem using the mysql query in the join function like this : 我能够在连接函数中使用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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM