CodeIgniter中的"SELECT ... IN(SELECT ...)"查询

Hun*_*ran 5 codeigniter

我有一个类似这样的查询:

SELECT username 
FROM users 
WHERE locationid IN 
  (SELECT locationid FROM locations WHERE countryid='$')
Run Code Online (Sandbox Code Playgroud)

$是我从最终用户获得的值.

我怎么能在CodeIgniter中运行此查询?我在CodeIgnite的用户指南中找不到解决方案.

非常感谢你的回答!

问候!

Cri*_*tiC 7

你看这里.

基本上你必须做绑定参数:

$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)"; 

$this->db->query($sql, '__COUNTRY_NAME__');
Run Code Online (Sandbox Code Playgroud)

但是,就像Mr.E所说,使用连接:

$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?"; 

$this->db->query($sql, '__COUNTRY_NAME__');
Run Code Online (Sandbox Code Playgroud)


Hai*_*ood 5

请注意,这些解决方案使用Code Igniter Active Records 类

此方法使用您希望的子查询,但您应该对$countryId自己进行消毒!

$this->db->select('username')
         ->from('user')
         ->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
         ->get();
Run Code Online (Sandbox Code Playgroud)

或者这种方法会使用连接来完成,并会为您清理数据(推荐)!

$this->db->select('username')
         ->from('users')
         ->join('locations', 'users.locationid = locations.locationid', 'inner')
         ->where('countryid', $countryId)
         ->get();
Run Code Online (Sandbox Code Playgroud)


小智 5

另外,要注意 - Active Record Class也有一个$this->db->where_in()方法.


xin*_*yue 2

我认为你可以创建一个简单的 SQL 查询:

$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
Run Code Online (Sandbox Code Playgroud)

然后就可以正常使用了。