2012-08-06 33 views
5

所以我有兩個表,我想從表1中的所有行滿足where子句的條件,然後加入他們與基於連接的表二條件。in codeigniter我如何做一個連接與where子句

這裏的示例表:

table1: 

col1 col2 col3 
1  a  val1 
2  b  val2 
3  c  val3 

table2: 

col1 col3 
1  someval1 
2  someval2 
3  someval3 

現在我要搶在表1中,其中的col1 = 2的所有行,並從表2,其中table2.col1 = table1.col1與行加入這些行。那有意義嗎?

+0

roytuts.com/codeigniter-join-example/ – user3470953 2016-05-28 03:41:54

回答

13

這已經有一段時間,因爲我寫了CI,但按照this docs page,您的解決方案可能是這樣的:

$this->db->select('*'); 
$this->db->from('table1'); 
$this->db->join('table2', 'table1.col1 = table2.col1'); 
$this->db->where('table1.col1', 2); 

$query = $this->db->get(); 

note這個答案決不能被解釋爲使用代碼點火器的認可;-)

+0

亞我在想,太多,除了我wasnn't知道where子句將適用於表1中,而不是加入的表1和表2 – user1549397 2012-08-06 02:11:20

+0

這與你的數據庫驅動程序如何編譯查詢有關。但幾乎在所有情況下,首先應用where子句,以便查詢只在匹配where子句的一行上執行連接。 – 2012-08-06 02:13:52

+1

換句話說,它會注意到它可以通過先將where子句應用於table1中的行來避免工作,然後*然後*執行連接。這就是我們所說的*構建查詢執行計劃*。在大多數情況下,ON和WHERE子句的處理方式相似;通常它是以非常有效的方式完成的。 – 2012-08-06 02:15:29

2

試試這個:

$this->db->select('*'); // Select field 
$this->db->from('table1'); // from Table1 
$this->db->join('table2','table1.col1 = table2.col1','INNER'); // Join table1 with table2 based on the foreign key 
$this->db->where('table1.col1',2); // Set Filter 
$res = $this->db->get(); 

希望它能幫助:)

0
$this->db->select('book_id, book_name, author_name, category_name'); 
$this->db->from('books'); 
$this->db->join('category', 'category.category_id = books.category_id'); 
$this->db->where('category_name', 'Self Development'); 
$query = $this->db->get(); 

// Produces SQL: 
select book_id, book_name, author_name, category_name from books 
join category on category.category_id = books.category_id 
where category_name = "Self Development"