2011-06-11 169 views
4

我有一個類似的查詢:「SELECT ... IN(SELECT ...)」 查詢CI中

SELECT username 
FROM users 
WHERE locationid IN 
    (SELECT locationid FROM locations WHERE countryid='$') 

$是一個值我從最終用戶獲得。

如何在CodeIgniter中運行此查詢?我無法在CodeIgnite的用戶指南中找到解決方案。

非常感謝你的回答!

問候!

+1

只是說一個說說連接>子選擇:'從用戶選擇用戶名 內部連接位置 users.locationid = locations.locationid where countryid ='$' – YXD 2011-06-11 11:07:10

回答

2

我認爲你可以創建一個簡單的SQL來查詢。

$sql="select username from user where id in (selce id from idtables)"; 
$query=$this->db->query($sql); 

然後就像normmall使用。

7

Look here

基本上你所要做的綁定PARAMS:

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

$this->db->query($sql, '__COUNTRY_NAME__'); 

但是,像Mr.E說,使用加入:

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

$this->db->query($sql, '__COUNTRY_NAME__'); 
3

注意,這些解決方案使用Code Igniter Active Records Class

這種方法使用你想要的子查詢,但你應該自己清理$countryId

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

或者這種方法將它使用的連接和消毒將數據給你(建議)呢!

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