【问题标题】:How to use correlated subquery into Active record query in Codeigniter如何在 Codeigniter 中将相关子查询用于活动记录查询
【发布时间】:2017-04-11 04:48:41
【问题描述】:

我正在努力从不同的表格中获取客户详细信息。我已经创建并测试了这个查询,它工作正常。问题是如何用户将此查询(转换)为 Active Records 查询。谢谢你。

            SELECT c.cust_id, `c`.`cust_contact_name`, `c`.`cust_active_flag`, 
            (select COUNT(`pm`.`cust_id`)  from property_master as pm 
            Where pm.cust_id = c.cust_id) as prop_count,
            (select a.addr_phoneno1 from address as a
            WHERE a.cust_id = c.cust_id AND a.addr_type_flag IN ('C', 'CP')) as cust_phone,
            (select count(ci.cust_id) from customer_inquiry as ci
            WHERE ci.cust_id = c.cust_id) as inquiry_count,
            (select max(inq_date) from customer_inquiry as ci
            WHERE ci.cust_id = c.cust_id) as last_inq_date
            FROM customer as c
            GROUP BY c.cust_ID

【问题讨论】:

  • @hekmat 先生,您能帮忙吗

标签: php mysql codeigniter activerecord correlated-subquery


【解决方案1】:

CodeIgniter 活动记录类不直接支持子查询。您可以使用任何 3rd 方库,例如 NTICompass CodeIgniter-Subqueries$this->db->query(); 来执行您的查询。

不过,您可以使用以下方式。但我会建议使用$this->db->query();

$this->db->select('c.cust_id, `c`.`cust_contact_name`, `c`.`cust_active_flag`, 
            (select COUNT(`pm`.`cust_id`)  from property_master as pm ' Where pm.cust_id = c.cust_id) as prop_count, (select a.addr_phoneno1 from address as a
            WHERE a.cust_id = c.cust_id AND a.addr_type_flag IN ('C', 'CP')) as cust_phone,
            (select count(ci.cust_id) from customer_inquiry as ci
            WHERE ci.cust_id = c.cust_id) as inquiry_count,
            (select max(inq_date) from customer_inquiry as ci
            WHERE ci.cust_id = c.cust_id) as last_inq_date)
         ->from('customer c');
$this->db->group_by('c.cust_ID');
$result = $this->db->get();

【讨论】:

  • 感谢@Bikram 但我正在寻找除直接使用查询之外的其他选项。
  • 您可以使用任何第三方 CI 库。
  • 你能推荐任何人或直接链接看看吗?
  • 我已经更新了答案,链接到一个图书馆。
猜你喜欢
  • 2011-08-28
  • 2016-01-08
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
相关资源
最近更新 更多