【问题标题】:Joining tables with duplicates from 1st table Code Igniter Active Records从第一个表 Code Igniter Active Records 连接具有重复项的表
【发布时间】:2014-04-09 20:42:03
【问题描述】:

在我的 PHP 代码点火器项目上工作,我正在实现一个在线购物车,我想加入 PRODUCT 和 PRODUCT_IMAGE 的两个表。 产品包含除“图像”之外的产品属性,并且 PRODUCT_IMAGE 包含针对每个“产品 ID”的图像 我有多个图像存储在 PRODUCT_IMAGE 中,每个“product_id”是表 PRODUCT_IMAGE 中的 FOREIGN KEY

我想使用 ACTIVE RECORDS 编写这样一个查询,以便它为 PRODUCT 中的每个产品提供仅一个来自 PRODUCT_IMAGE 的图像。

到目前为止,我已经尝试过:

//$cat_num is category_number of the products against which we want to get Products  
 $this->db->select('distinct(product_image.product_id),product_image.image,product.name');
$this->db->from('product');
$this->db->where('product.category',$cat_num);
$this->db->join('product_image', 'product.id = product_image.product_id','left');

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

【问题讨论】:

    标签: php mysql database codeigniter activerecord


    【解决方案1】:

    试试这个代码:

    $this->db->select('product_image.product_id, product_image.image, product.name')
             ->from('product')
             ->join('product_image', 'product.id = product_image.product_id')
             ->where("product.category", $cat_num);
    $query = $this->db->get();
    
    if ($query->num_rows() > 0){
        return $query->result());
    }
    

    【讨论】:

    • 我认为你没有得到问题。问题是我必须为每个产品只获取一个图像行。实际上,有很多产品图像,我们只想显示一个跨度>
    【解决方案2】:

    使用“group by”语句为我解决了问题

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 1970-01-01
      • 2014-03-23
      • 2014-11-14
      • 1970-01-01
      • 2022-11-13
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多