SELECT *
FROM fx_dirprocess
WHERE `pro_id` IN (SELECT MAX(`pro_id`) FROM fx_dirprocess GROUP BY name)
AND `co_id`=$company;
如何在codeigniter中构造此查询
以下我尝试过没有用过:
$this->db->select('*')->from('fx_dirprocess');
$this->db->where('`pro_id` IN (SELECT MAX(`pro_id`)
FROM `fx_dirprocess`
GROUP BY `name`,’co_id’,$company)’, NULL, FALSE);
$this->db->select_max(‘pro_id’)->group_by(‘name’);
$where_clause = $this->db->get_compiled_select('fx_dirprocess');
$this->db->select('*');
$this->db->from('fx_dirprocess');
$this->db->where("`pro_id` IN ($where_clause)", NULL, co_id,$company);
答案 0 :(得分:2)
// make A subquery :-
$this->db->select_max('pro_id')->from('fx_dirprocess')->group_by('name');
$subQuery = $this->db->get_compiled_select();
// Now the main query is :-
$this->db->select('*')->from('fx_dirprocess');
$this->db->where("pro_id IN ($subQuery)", NULL, FALSE);
$this->db->get()->result();
谢谢!
答案 1 :(得分:1)
您正在通过GROUP BY
来选择MAX
值,但它不会给出确切的值。你喜欢以下
$sql_query = "SELECT * FROM `fx_dirprocess` WHERE `pro_id` IN (SELECT MAX(`pro_id`) FROM `fx_dirprocess`) AND `co_id` = '{$company}'";
$query = $this->db->query($sql_query);
return ($query->num_rows() > 1) ? $query->row() : $query->result();
答案 2 :(得分:0)
为了受到CI的Querybuilder的保护,您可以使用get_compiled_select
以下内容应该有效
$query = $this->db
->select('*')
->from('fx_dirprocess')
->where('pro_id IN ('.$this->db->select_max('pro_id')->from('fx_dirprocess')->group_by('name')->get_compiled_select().')', NULL, false)
->where('co_id', $company)
->get();