在codeigniter中如何使用where子句进行连接

时间:2012-08-06 01:50:03

标签: php mysql codeigniter join where-clause

所以我有两个表,我希望得到表1中满足where子句条件的所有行,然后根据连接条件将它们与表2连接起来。

以下是示例表:

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的所有行,并使用table2中的行连接这些行,其中table2.col1 = table1.col1。这有意义吗?

3 个答案:

答案 0 :(得分:16)

自从我编写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 此答案绝不能被视为对使用Code Igniter的认可; - )

答案 1 :(得分:3)

试试这个:

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

希望有所帮助:)

答案 2 :(得分: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"