Codeigniter Active Record 中的子查询
Posted
技术标签:
【中文标题】Codeigniter Active Record 中的子查询【英文标题】:Sub-queries in Code Igniter Active Records 【发布时间】:2016-03-15 19:52:10 【问题描述】:我正在尝试在 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 活动记录。谢谢
【问题讨论】:
参考:arjunphp.com/… 和 ***.com/questions/6047149/… 谢谢,第一个链接让我设法创建了查询 【参考方案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;
【讨论】:
【参考方案2】:在 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
【讨论】:
【参考方案3】:我设法让这个工作,诚然使用相当松散类型的 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();
【讨论】:
以上是关于Codeigniter Active Record 中的子查询的主要内容,如果未能解决你的问题,请参考以下文章
使用 CodeIgniter Active Record 语句
CodeIgniter Active Record 与常规查询
CodeIgniter Active Record 中的 SQL 注释?