CI MySQL查询连接表和where语句不返回所有行

时间:2017-04-11 06:06:58

标签: php mysql codeigniter join

我有3个表要加入,但是当我在第三个表上使用where语句,而第三个表没有它时,它不会返回第一个和第二个表中的行,即使我' m使用左连接。

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,因为没有数据table_2和table_3中的acc_PID ='4',但是我希望结果返回帐户4,即使表2和表3中没有帐户4的数据,没有$ this-> db-> where('c .trans_location','1'),结果也显示了帐号4,但是使用where location语句它不返回表1中的行,即使我使用了左连接,它也不应该从表1返回结果吗? / p>

提前谢谢。

1 个答案:

答案 0 :(得分:4)

尝试在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 Account1和Account 2

希望这会对你有所帮助。

相关问题