【问题标题】:Joining 4 tables with Mysql and Codeigniter使用 Mysql 和 Codeigniter 连接 4 个表
【发布时间】:2012-08-08 13:38:00
【问题描述】:

我有 4 张桌子,这都是关系,是的,他们彼此相爱:p

  • 产品
  • 产品类别
  • 产品类别关系
  • 产品图片

我想在一个查询中加入这 4 个表,这是我的 Codeigniter 代码;

function list_products($limit = 10, $offset = 0, $category)
{
    $this->db->select('p.url, p.name, p.title, i.image');
    $this->db->from('products p');
    $this->db->join('product_categories c','c.id = r.category_id',
                    'left');
    $this->db->join('product_category_relations r',
                    'r.category_id = c.id','left');
    $this->db->join('product_images i',
                    'p.id = i.product_id AND i.default = 1','left');
    $this->db->where('c.url',$this->category_url.$category);
    $this->db->limit($limit,$offset);
    return $this->db->get()->result();
}

当我执行这个函数/查询时,结果是关于定义“r”的错误。

“on 子句”中的未知列“cms_r.category_id”

查询:

选择p.url, p.name, p.title, i.image FROM (cms_products p) 左连接 cms_product_categories c ON c.id = cms_r.category_id 左连接 cms_product_category_relations r ON r.category_id = c.id 左连接 cms_product_images 我打开 p.id = i.product_id AND i.default = 1 其中c.url = 'categori/yilbasi' 限制 12

你能帮帮我吗?

【问题讨论】:

    标签: php mysql codeigniter join


    【解决方案1】:

    您在使用后将r 分配为与product_category_relations 相似。

    你在这里写:

    $this->db->join('product_categories c','c.id = r.category_id','left');
    

    但是r 是什么?你只在下一个陈述中回答这个问题。

    $this->db->join('product_category_relations r','r.category_id = c.id','left');
    

    如果您需要具体答案,请提供示例 SQL 创建脚本。

    【讨论】:

    • R 是 product_category_relations。如您所见,我没有使用“AS”。
    • @R.CanserYanbakan 但是你说Rproduct_category_relations 你使用了R之后。
    • 我知道它应该是什么,我在问它会怎样......那么,我们怎么能做到这一点呢? :)
    • 那么,请为这四个表提供您的SQL Create Script。几乎没有人会为了回答一个问题而花时间自己创建包含四个表的数据库。
    • 你在开玩笑吗 :) 我要求提供理论信息,每个了解我的问题的人都可以轻松猜出发生了什么。
    【解决方案2】:

    @Edward Ruchevits 您的查询没有加入,因为 r.category_id 在加入 product_category_relations r 后定义,您需要 productsproduct_categories 之间的关系,然后您的查询类似于

    $this->db->join('product_categories c','c.product_id = p.id','left');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多