为不同的列连接两次相同的表

时间:2015-02-04 10:51:17

标签: php mysql codeigniter join

我有一个餐桌产品和一个餐桌位置。 products表有两列pickLocation和recLocation。在位置表中我有id和name列。 pickLocation和recLocation具有来自位置表的id。我如何在codeigniter中加入表格。

这是我的代码

$this->db->select("locations.name as plname");
$this->db->select("locations.name as rcname");
$this->db->join("locations","locations.id=products.pickLocation","LEFT");
$this->db->join("locations","locations.id=products.recLocation","LEFT");

这是产品表

+----+--------------+-------------+
| Id | pickLocation | recLocation |
+----+--------------+-------------+
|  1 |           12 |          23 |
|  2 |           12 |          12 |
+----+--------------+-------------+

这是位置表

+----+-----------+--+
| Id |   name    |  |
+----+-----------+--+
| 12 | Location1 |  |
| 23 | Location2 |  |
+----+-----------+--+

我想要这样的结果

+-----------------------+
| 1 Location1 Location2 |
+-----------------------+
| 2 Location1 Location1 |
+-----------------------+

2 个答案:

答案 0 :(得分:4)

使用别名。此外,除了join子句之外,您的产品表永远不会出现。它也应该在from。

$query = $this->db->select("p.id, l1.name as plname, l2.name as rcname")
                 ->join("location l1", "l1.id = p.pickLocation", "left")
                 ->join("location l2", "l2.id = p.recLocation", "left")
                 ->get("product p"); 

答案 1 :(得分:2)

您需要使用别名,以便能够区分这两个连接。尝试这样的事情:

$this->db->select("pickLoc.name as plname");
$this->db->select("recLoc.name as rcname");
$this->db->join("locations as pickLoc","pickLoc.id=products.pickLocation","LEFT");
$this->db->join("locations as recLoc","recLoc.id=products.recLocation","LEFT");