【问题标题】:SQL Query Join in CodeIgniterCodeIgniter 中的 SQL 查询联接
【发布时间】:2020-11-28 17:02:16
【问题描述】:

我有这个查询,我需要它以 CodeIgniter 方式(查询生成器)。我知道如何使用标准的 query builder class 函数,但是我很难找到一种方法来使用 CI Query Builder 类构建带有内部 SELECT 子句的 LEFT JOIN

SELECT * 
FROM   sma_products p 
       LEFT JOIN (SELECT product_id, 
                         Count(*) 
                  FROM   sma_sale_items 
                  GROUP  BY product_id) s 
              ON p.id = s.product_id 
ORDER  BY ` Count(*) ` DESC 

【问题讨论】:

  • $this->db->select('*'); $this->db->from('sma_products'); $this->db->join('sma_sale_items','sma_sale_items.product_id =sma_products.product_id','left'); $this->db->group_by('sma_products.product_id'); $query = $this->db->get(); $this->db->order_by('experience_seats.experience_id', 'asc');
  • 你可以像这样使用左连接
  • @ArslanAhmad 您缺少 LEFT JOIN 中的 SELECT 子句
  • 只是出于好奇:您是否阅读了我的回答,是否有帮助?

标签: mysql sql codeigniter


【解决方案1】:

使用 CI 查询构建器创建此 SQL 的难点在于左连接内的选择部分。您可以使用 join() 函数将 $table 参数替换为 SELECT 部分来构建它:

join($table, $cond[, $type = ''[, $escape = NULL]]) 参数:

    $table (string) – Table name to join
    $cond (string) – The JOIN ON condition
    $type (string) – The JOIN type
    $escape (bool) – Whether to escape values and identifiers

这是最终的 CI 代码:

$q=$this->db1   ->select ('*')
                ->join('(
                                select `product_id`
                                ,count(*) 
                                from `sma_sale_items`
                                group by `product_id`
                            ) s','p.id = s.product_id','left')
                ->order_by('count(*)', 'DESC')
                ->get('sma_products p');

return $q->result();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多