[英]joining the same table twice for different columns
我有一張桌子產品和一張桌子位置。 產品表具有兩列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 |
+-----------------------+
使用別名。 另外,除了join子句外,您的產品表永遠不會出現。 它也應該在從。
$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");
您需要使用別名,以便能夠區分這兩個聯接。 嘗試這樣的事情:
$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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.