简体   繁体   中英

How to use `where` and `in` clause together in php codeigniter?

I have two tables:

1) Users
2) Trustmembers

I want to take all userId's from Trustmembers and compare with Id of Users table and then i want to print all the names from Users table of matching id's.

In sql I can write the query like

select name from users where Id IN(select userId from Trustmembers); 

How to write the same query in Model(MVC) of php codeigniter to get the same result?

Or any other way except using Where_in??

You can do like this,

METHOD 1:

$this->db->select('name')->from('users');
$this->db->where('Id IN (SELECT userId FROM `Trustmembers`)', NULL, FALSE);
$result = $this->db->get();

NULL, false will be used to not escape the query as by default.

METHOD 2

$this->db->select('name')->from('users');
$this->db->where_in('Id', 'SELECT userId FROM `Trustmembers`');
$result = $this->db->get();

METHOD 3 : subquery library

$this->db->select('name')->from('users');
$subquery = $this->subquery->start_subquery('where_in');
$subquery->select('userId')->from('Trustmembers');
$this->subquery->end_subquery('Id', FALSE);
$result = $this->db->get();

I hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM