2017-04-11 79 views
3

我有3個表我想要加入,但是當我在第三個表上使用where語句,並且第三個表沒有它時,它不即使我正在使用左連接,也會返回第一個和第二個表中的行。CI MySQL查詢連接表和其中語句不返回所有行

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(); 

現在從上面的數據,如果我使用($這 - > DB->其中( 'c.trans_location', '1')),結果不會因爲沒有返回帳戶4在表2和表3中,acc_PID ='4'的數據,但是我希望結果也返回帳戶4,即使表2和表3中沒有帳戶4的數據,也沒有$ this-> db-> where('c .trans_location','1'),結果也顯示了帳戶4,但是使用where位置語句它不會返回表1中的行,即使我使用了左連接,也不應該返回表1的結果嗎?

預先感謝您。

+1

嘗試在連接中添加條件而不是where子句。 –

+0

這可能會幫助你http://stackoverflow.com/questions/15992236/codeigniter-join-with-multiple-conditions –

+0

@AmiteshKumar愚蠢的我!謝謝先生,請寫下您的答案,以便我可以接受它作爲答案。 – Charas

回答

3

嘗試在Join中添加條件,而不是在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 

這會給我兩個有分帳戶1和賬戶2

希望這會幫助你。

+0

謝謝你的回答。關係是從table_2.journal_account到table_1.acc_PID,所以我添加了AND爲$ this-> db-> join(table_3 c','b,trans_PID = c.trans_PID和c.trans_location = 1');如果我沒有使用左連接,它不返回表2和3中沒有關係的帳號4,如果我使用左邊它返回帳號4,但也從表3中得出除'1 」。 – Charas

+0

@Charas我在回答中添加了查詢,希望如果是,請接受答案。 –

+0

是的,謝謝你,結果你的代碼工作得很好,是什麼讓我的結果返回table_3中的所有數據是因爲我使用了SELECT(SUM(CASE WHEN table_3 bla blac,忘記添加CASE WHEN和transaction_location = 1)。很多你的幫助。 – Charas