【问题标题】:codeigniter active records aggregate not working [duplicate]codeigniter活动记录聚合不起作用[重复]
【发布时间】:2017-06-21 10:09:25
【问题描述】:

我正在使用 Codeigniter,我想做的是一个返回连接表 (item_gallery) 的查询,gallery_id 是最小值。而主查询按项目 post_date 的 desc 排序

下面的代码 group_by 选择 item_gallery gallery_id 的随机值。但我想要 item_gallery gallery_id 的最低值。

  public function shopItems($id) {

    $this->db->select("*,MIN(item_gallery.gallery_id)");
    $this->db->from('items');
    $this->db->join('item_gallery', 'items.id = item_gallery.item_id', 'left');
    $this->db->where('items.user_id', $id);     
    $this->db->order_by('items.post_date', 'Desc');
    $this->db->group_by("item_gallery.item_id");
    $query = $this->db->get();
    return $query->result();
}

数据库结构

项目表

|    id    |  slug  |  user_id  |  post_date |

|    12    |  test  |    111    |  12/5/2017 |

项目库

| gallery_id |  item_id  |     image     | 

|     121    |    12     |  profile.png  |   -- i want this record selected
|     122    |    12     |  gallery.png  | 

【问题讨论】:

    标签: codeigniter activerecord codeigniter-3


    【解决方案1】:

    您是否尝试过在连接条件中使用内部查询的 MIN?

        $this->db->select("*,MIN(item_gallery.gallery_id)");
        $this->db->from('items');
        $this->db->join('item_gallery', 'items.id = ( SELECT MIN(item_gallery.gallery_id) id FROM item_gallery WHERE items.id = item_gallery.item_id )', 'left');
        $this->db->where('items.user_id', $id);
        $this->db->order_by('items.post_date', 'Desc');
        $this->db->group_by("item_gallery.item_id");
        $query = $this->db->get();
    

    【讨论】:

    • 不返回图片。
    • 更改 $this->db->select(",MIN(item_gallery.gallery_id)");到 $this->db->select("items.,item_gallery.image");
    • 添加上述代码后也无法正常工作,当有 3 个项目仅显示一个项目且图像不可见时,此代码会出现其他问题
    • 刚刚测试了代码。它对我来说工作正常(第一个答案)。
    • 这将只返回 item_gallery 中的一行(item_gallery gallery_id 的最小值)以及相关的项目行。如果您想要所有匹配的行,则需要更正问题。
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2014-02-25
    • 2016-03-26
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多