在Codeigniter的查询构建器中重写数据库查询

时间:2019-01-29 10:37:37

标签: php codeigniter

我正在尝试在Codeigniter的查询生成器中重写现有的数据库查询,如何解决WHERE EXISTS(我认为这是问题所在)?

这是我要重写的原始查询:

id  name        parent_id 
74  category15  47
75  category16  47
76  category19  47
77  category20  47

这是我到目前为止得到的:

$query = $this->db->query('SELECT p_customer.*' .
        ' FROM p_customer' .
        ' WHERE EXISTS (' .
        'SELECT null' .
        ' FROM p_customer_group_rel' .
        ' WHERE p_customer_group_rel.customer_group_id=' . $e_id.
        ' AND p_customer_group_rel.customer_id = p_customer.id' .
        ')' .
        ' AND p_customer.deleted IS NULL' .
        ' AND p_customer.id > 0' .
        ' ORDER BY p_customer.full_name'
    );

我从第一个查询中得到的结果是对象数组。 这是我从查询中得到的:

$query = $this->db
        ->select('p_customer.*')
        ->from('p_customer')
        ->where('EXISTS(SELECT null FROM p_customer_group_rel WHERE 
p_customer_group_rel.customer_group_id= ' . $e_id . ' AND 
p_customer_group_rel.customer_id = p_customer.id)')
        ->where('p_customer.deleted is NULL')
        ->where('p_customer.id > 0')
        ->order_by('p_customer.full_name');
        ->get();

这不是我想要的,有什么帮助吗? :)

1 个答案:

答案 0 :(得分:0)

也许这不是最好的解决方案,但是我做了以下工作,并且有效:

$sub_q = 'SELECT null FROM p_customer_group_rel WHERE p_customer_group_rel.customer_group_id=' . $e_id . ' AND p_customer_group_rel.customer_id = p_customer.id';
$query = $this->db ->select('p_customer.*') ->from('p_customer') ->where('EXISTS(' . $sub_q . ')') ->where('p_customer.id >', 0) ->where('p_customer.deleted', NULL) ->order_by('p_customer.full_name') ->get();