代码点火器活动记录中的子查询

时间:2015-12-10 08:58:26

标签: mysql codeigniter

我正在尝试在CI Active Records中编写以下MySql查询。该查询使用了一个子查询,但我正在努力解决这个问题。

有问题的查询:

SELECT 
                COUNT(*) AS no_skus, 
                pd_vendor AS brand, 
                (SELECT COUNT(DISTINCT(pd_model_code)) 
                FROM product_data
                WHERE pd_vendor = PD.pd_vendor ) AS unique_models
                FROM product_data PD
                GROUP BY pd_vendor
                ORDER BY 
                COUNT(*) DESC";

有人可以建议如何将其编写/结构化为CI Active Record。谢谢

3 个答案:

答案 0 :(得分:1)

检查一下:

SELECT COUNT(*) AS no_skus, 
        pd_vendor AS brand, 
        (SELECT COUNT(DISTINCTpd_model_code) FROM product_data WHERE pd_vendor = PD.pd_vendor ) AS unique_models
FROM product_data 
GROUP BY pd_vendor
ORDER BY no_skus DESC;

答案 1 :(得分:1)

在Codeigniter方式中,您可以像这样编写此子查询

function getProductData(){
$this->db->select("COUNT(*) AS no_skus,pd_vendor AS brand,(SELECT COUNT(DISTINCT(pd_model_code)) FROM product_data
                WHERE pd_vendor = PD.pd_vendor ) AS unique_models",false);// second parameter for escape--we disable to escap as codeigniter adding ` to protect identifiers
            $this->db->from("product_data PD");
            $this->db->group_by('pd_vendor');
            $this->db->order_by('no_skus', 'DESC');
            $result_arr=$this->db->get()->result_array();
return $result_arr

}

答案 2 :(得分:0)

我设法让这个工作,不可否认使用相当松散的类型Active Record语法。代码在这里:

// Main Query
$this->db->select('
        COUNT(*) AS no_skus,
        pd_vendor AS brand')
        ->from('product_data PD')
        ->group_by('pd_vendor');

// Sub Query
$this->db->select('(SELECT
        COUNT(DISTINCT(pd_model_code)) 
        FROM product_data
        WHERE pd_vendor = PD.pd_vendor ) 
        AS unique_models');
$subQuery = $this->db->last_query();

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