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

Cha*_*ras 3 php mysql join codeigniter

我有 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();
Run Code Online (Sandbox Code Playgroud)

现在从上面的数据来看,如果我使用($this->db->where('c.trans_location', '1')),结果不会返回Account 4,因为没有acc_PID ='4'的数据在 table_2 和 table_3 中,但是我希望结果也返回帐户 4,即使表 2 和表 3 中没有帐户 4 的数据,没有 $this->db->where('c.trans_location', '1' ),结果也显示了帐户 4,但是使用 where location 语句,即使我使用了左连接,它也不会返回表 1 中的行,它不应该也返回表 1 中的结果吗?

先感谢您。

Ami*_*mar 5

尝试在 Join 中添加条件而不是在 where 子句上。如果在 where 子句中写条件,它会在 join 后添加条件,表示过滤后过滤,

或不使用左连接并最后添加 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
Run Code Online (Sandbox Code Playgroud)

并且这也:

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
Run Code Online (Sandbox Code Playgroud)

这会给我两个帐户 Account1 和帐户 2

希望这会帮助你。