首页 文章

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

提问于
浏览
6

所以我有两个表,我想从表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 回答

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

    请注意,此答案绝不能被视为与Code Igniter合作的认可;-)

  • 0

    试试这个 :

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

    希望能帮助到你 :)

  • 3
    $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"
    

相关问题