【求助】SQL语句,求大神帮忙转换为Active Record
SQL 语句如下,自己一直没做好,求大神帮忙转换成Active Record格式,万分感谢:
select * from (select user.*,ifnull(admin_member.role,0) as role,admin_member.id as aid from user left join admin_member on admin_member.user_id = user.id) as ut where ut.username LIKE '%%' and ut.role=1 ORDER BY ut.role desc,ut.id asclimit 0,5
自己顶一个 :L自己顶一个 本帖最后由 aneasystone 于 2015-7-13 15:40 编辑
首先,你没有必要使用内联视图子查询,另外WHERE条件中的 ut.username LIKE '%%' 似乎也没有意义。所以你的SQL可以简化成下面这样:
SELECT
u.*,
IFNULL(am.`role`, 0) `role`,
am.id aid
FROM `user` u
LEFT JOIN admin_member am
ON am.user_id = u.id
WHERE am.`role` = 1
ORDER BY am.`role` DESC, u.id ASC
LIMIT 0,5
这样SQL就是一个简单的JOIN语句,可以采用类似于下面的AR代码(手工打的,没测试):
$this->db->select('*');
$this->db->from('user');
$this->db->join('admin_member', 'admin_member.user_id = user.id');
$this->db->where('role', 1);
$this->db->order_by('role desc, id asc');
$this->db->limit(5);
$query = $this->db->get();
aneasystone 发表于 2015-7-13 15:31
首先,你没有必要使用内联视图子查询,另外WHERE条件中的 ut.username LIKE '%%' 似乎也没有意义。所以你的 ...
不好意思,我忘了说明具体情况了,{:soso_e106:}
1. role 字段只存在于admin_member;
2.admin_member只存储role=1的元素,表内并无role = 0的元素
你写的这种方法我最初的时候用过,用where无法进行有效过滤,所以,我写了子查询。。。
{:soso_e113:}http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113http://imgstore01.cdn.sogou.com/app/a/100520032/e113
还好,目前问题已经解决了,我在函数内部对sql语句进行了组装,没有使用Active Record了
页:
[1]