“SELECT ... IN(SELECT ...)” 查询CI中
问题描述:
我有一个类似的查询:“SELECT ... IN(SELECT ...)” 查询CI中
SELECT username
FROM users
WHERE locationid IN
(SELECT locationid FROM locations WHERE countryid='$')
$是一个值我从最终用户获得。
如何在CodeIgniter中运行此查询?我无法在CodeIgnite的用户指南中找到解决方案。
非常感谢你的回答!
问候!
答
我认为你可以创建一个简单的SQL来查询。
$sql="select username from user where id in (selce id from idtables)";
$query=$this->db->query($sql);
然后就像normmall使用。
答
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__');
答
注意,这些解决方案使用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();
只是说一个说说连接>子选择:'从用户选择用户名 内部连接位置 users.locationid = locations.locationid where countryid ='$' – YXD 2011-06-11 11:07:10