【问题标题】:CodeIgniter Active Record use "USING" in queryCodeIgniter Active Record 在查询中使用“USING”
【发布时间】:2014-03-04 04:16:41
【问题描述】:

我正在尝试使用 CodeIgniter 中的 Active Record 复制以下查询,但我找不到文档中的位置或搜索您如何在查询中使用 USING

SELECT * 
FROM categories C
LEFT OUTER JOIN motorcycle_brands MB
USING ( CatID ) 
LEFT OUTER JOIN powersport_categories PS
USING ( CatID ) 
WHERE C.CatID = :uniqueID

这就是我现在拥有的:

$this->db->select('*');
$this->db->from('categories C');
$this->db->join('motorcycle_brands MB', 'CatID', 'left outer');
$this->db->join('powersport_categories PS', 'CatID', 'left outer');
$this->db->where('C.CatID =', $this->option_id);
$suboptions = $this->db->get();

我尝试过改变

$this->db->join('motorcycle_brands MB', 'USING (CatID)', 'left outer');
$this->db->join('powersport_categories PS', 'USING (CatID)', 'left outer');

【问题讨论】:

  • 您的代码是否有任何错误,您在下面提到This is what I have now:

标签: php mysql codeigniter


【解决方案1】:

在活动记录类中使用 USING 没有对 JOIN 的内置支持。你能做的最好的就是改变“system/database/DB_active_rec.php”这个文件中的join()函数。

请参阅此问题以获取完整参考。 codeigniter active records join with using?

【讨论】:

    【解决方案2】:

    USING 子句用于如果多个列共享相同的名称但您不想使用所有这些公共列进行连接。 USING 子句中列出的列在语句中不能有任何限定符,包括 WHERE 子句:

    ON 子句用于连接两个表中列名不匹配的表。连接条件从 WHERE 子句中的过滤条件中移除:

    所以你的代码应该是,

    $this->db->select('*');
    $this->db->from('categories C');
    $this->db->join('motorcycle_brands MB', 'MB.CatID = C.Id', 'left outer');
    $this->db->join('powersport_categories PS', 'C.Id = PS.CatID ', 'left outer');
    $this->db->where('C.CatID =', $this->option_id);
    $suboptions = $this->db->get();
    

    【讨论】:

    • 这给了我一个错误,但自从我发布了这个问题后我就明白了,但现在我的问题是我在 motorcycle_brandspowersport_categories 中都有 SubIDSubName 所以它是返回motorcycle_brands 的空值,但返回powersport_categories 中的所有行我需要弄清楚接下来要做什么来解决这个问题
    • 由于列名而出错。我刚刚发布了带有虚拟列名的答案。希望您可以像在表格中一样更改列名。
    猜你喜欢
    • 2016-03-15
    • 2012-04-17
    • 2013-02-22
    • 2011-10-22
    • 2014-06-26
    • 2013-01-09
    • 1970-01-01
    • 2017-03-30
    • 2011-03-06
    相关资源
    最近更新 更多