【问题标题】:in codeigniter how do i do a join with a where clause在codeigniter中我如何使用where子句进行连接
【发布时间】:2012-08-03 00:50:12
【问题描述】:

所以我有两个表,我想从表 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。这有意义吗?

【问题讨论】:

  • roytuts.com/codeigniter-join-example/

标签: php mysql codeigniter join where-clause


【解决方案1】:
$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"

【讨论】:

    【解决方案2】:

    我写 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 的认可;-)

    【讨论】:

    • 是的,我也在考虑这个问题,但我不确定 where 子句是否将应用于表 1,而不是表 1 和表 2 的连接。
    • 这与您的数据库驱动程序如何编译它的查询有关;但几乎在所有情况下,都会先应用 where 子句,这样查询只会对匹配 where 子句的一行执行连接。
    • 换句话说,它会注意到它可以通过首先将 where 子句应用于 table1 中的行,然后 then 进行连接来避免工作。这就是我们所说的构建查询执行计划。大多数情况下,ON 和 WHERE 子句的处理方式类似;而且通常以非常有效的方式完成。
    【解决方案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();
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-05
      • 2015-09-19
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 2011-09-22
      相关资源
      最近更新 更多