我有3个表要联接,但是当我在第三个表上使用where语句,而第三个表没有它时,即使我使用的是left,它也不会返回第一和第二个表中的行加入.
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′)),结果将不会返回帐户4,因为没有acc_PID =’的数据table_2和table_3中的4′,但是即使表2和表3中没有帐户4的数据,我也希望结果也返回帐户4,而没有$this-> db-> where(‘c.trans_location’ ,’1′),结果也显示帐户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
AND这也是:
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 Account1和Account 2
希望这会帮助你.
标签:codeigniter,join,mysql,php
来源: https://codeday.me/bug/20191026/1933742.html