php 在 codeigniter 中,我如何使用 where 子句进行连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11821687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
in codeigniter how do i do a join with a where clause
提问by user1549397
so i have two tables, and i want to get all the rows from table 1 that meet the where clause conditions, and then join them with table two based on the join conditions.
所以我有两个表,我想从表1中获取满足where子句条件的所有行,然后根据连接条件将它们与表2连接。
here are the sample tables:
以下是示例表:
table1:
col1 col2 col3
1 a val1
2 b val2
3 c val3
table2:
col1 col3
1 someval1
2 someval2
3 someval3
now i want to grab all the rows in table 1 where col1 = 2, and join those rows with rows from table2 where table2.col1 = table1.col1. Does that make sense?
现在我想获取表 1 中 col1 = 2 的所有行,并将这些行与 table2 中的行连接起来,其中 table2.col1 = table1.col1。那有意义吗?
回答by Chris Trahey
It's been a while since I wrote CI, but as per this docs page, your solution might look like this:
我写 CI 已经有一段时间了,但根据这个文档页面,您的解决方案可能如下所示:
$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();
notethis answer is in no way to be construed as an endorsement of working with Code Igniter ;-)
请注意,此答案绝不能被解释为对使用 Code Igniter 的认可;-)
回答by Yagi
Try this :
尝试这个 :
$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();
Hope it helps :)
希望能帮助到你 :)
回答by Jah Yusuff
$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"

