codeigniter中的mysql查询不返回任何内容

时间:2018-04-27 14:29:17

标签: php codeigniter

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);

3 个答案:

答案 0 :(得分:2)

@Tejaswini请查看以下代码,希望对您有帮助。

// 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();