我有3个表要联接,但是当我在第三个表上使用where语句时,而第三个表格没有它,即使我使用左联接,它也不会返回第一个和第二个表格中的行。
Table 1
+---------+--------------+----------+
| acc_PID | acc_name | acc_type |
+---------+--------------+----------+
| 1 | Account 1 | 1 |
| 2 | Account 2 | 1 |
| 3 | Account 3 | 2 |
| 4 | Account 4 | 1 |
+---------+--------------+----------+
Table 2
+-------------+-----------------+-----------+
| journal_PID | journal_account | trans_PID |
+-------------+-----------------+-----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
+-------------+-----------------+-----------+
Table 3
+-----------+----------------+
| trans_PID | trans_location |
+-----------+----------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
+-----------+----------------+
// CI query
$this->db->join('table_2 b', 'a.acc_PID = b.journal_account', 'LEFT');
$this->db->join('table_3 c', 'b.trans_PID = c.trans_PID', 'LEFT');
$this->db->where('a.acc_type', '1');
$this->db->where('c.trans_location', '1');
$this->db->group_by('a.acc_PID');
$query = $this->db->get('table_1 a');
$result = $query->result();
从上面的数据来看,如果我使用($this->db->where('c.trans_location','1')),结果不会返回Account 4,因为表_2和表_3中没有acc_PID='4'的数据,但是我希望结果也返回Account 4——即使表2和表3中没有Account 4的数据,如果没有$this-->db->where,结果也显示Account 4,然而,对于where location语句,即使我使用了左联接,它也不会返回表1中的行,难道它也应该返回表1的结果吗?
提前谢谢。
尝试在Join中添加条件,而不是在where子句中添加条件。如果您在where子句中写入条件,它将在加入后添加条件意味着一个接一个的过滤器,
或者不要使用左联接,最后添加where条件。
还有一件事,我没有发现表1与tanle 2或表3有任何关系。如果journal_account
与表1有关系,那么它应该可以工作。
我自己尝试,这是我认为的解决方案:
SELECT * FROM `table1`
INNER JOIN table2 ON table2.journal_account = table1.acc_PID
INNER JOIN table3 ON table3.trans_PID = table2.trans_PID
WHERE table1.acc_type = 1 AND table3.trans_location = 1 GROUP BY table1.acc_PID
还有:
SELECT * FROM `table1`
INNER JOIN table2 ON table2.journal_account = table1.acc_PID
INNER JOIN table3 ON table3.trans_PID = table2.trans_PID AND table3.trans_location = 1
WHERE table1.acc_type = 1 GROUP BY table1.acc_PID
这将给我两个Accoun账户1和账户2
希望这对你有帮助。