【问题标题】:Codeigniter where not exists does not work不存在的 Codeigniter 不起作用
【发布时间】:2020-10-18 16:54:37
【问题描述】:

我正在从事 Codeigniter 项目,但遇到了一个问题。我希望我的模型上的函数为我带来来自 POST 表的数据,其中 CATEGORY 表中的 POST_ID 不为空,而不加入表,因此(不要带回 CATEGORY 表中 POST_ID 不存在的数据)。 所以我尝试了这个方法我怎么能得到这个结果?

code: // MyModel

function get_data() {
    
    
    $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';

    if ($id != null) {
        $this->db->where('ID',$id);
        $result =  $this->db->select('POST.ID,POST.DATE,'
        . ' TYPE.Post_Type P_TYPE,)
        ->join('TYPE', 'POST.TYPE_ID = TYPE.ID', 'left')
        ->order_by('POST.ID', 'DESC')
        ->where_in('POST.Post_Type  = type_1, type_2')
        ->where("NOT EXISTS(SELECT POST_ID FROM CATEGORY WHERE POST.ID=CATEGORY.POST_ID )", FALSE)
        ->get('POST');
    } 
    return $result;
}

感谢您的帮助

【问题讨论】:

    标签: php codeigniter eloquent codeigniter-3 eloquent-relationship


    【解决方案1】:

    如果您想要一个不为空的数据(意味着它存在),最好使用 IN,或者如果您正在寻找的答案是相反的,您也可以将其更改为 NOT IN。无论如何,我没有更改您的查询中的任何内容,我只是将 POST_ID 和 IN 放在 where 语句中

    function get_data() {
    
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        if ($id != null) {
    
            $in = array('type_1', 'type_2');
            $this->db->where('ID',$id);
            $this->db->select('POST.ID,POST.DATE,TYPE.Post_Type as P_TYPE', FALSE);
            $this->db->join('TYPE', 'POST.TYPE_ID = TYPE.ID', 'left');
            $this->db->order_by('POST.ID', 'DESC');
            $this->db->where_in('POST.Post_Type', $in);
            $this->db->where("POST.POST_ID IN(SELECT C.POST_ID FROM CATEGORY C )");
            $this->db->from('POST');
            $result = $this->db->get();
        } 
        return $result;
    }
    

    【讨论】:

    • 感谢您的回复我尝试了此代码,但我收到此错误:ORA-00933 SQL 命令未正确结束
    • 请尝试编辑后的代码,我将查询更改为与您的样式不同的样式。尝试更改 type1 和 type2 的 $in 值
    • 我编辑了代码但是这一行 $this->db->where("POST_ID IN(SELECT POST_ID FROM CATEGORY)");显示错误 ORA-00918:列定义不明确
    • 当我删除加入我得到这个错误 ORA-00904: invalid identifier
    • 现在试试这个,我把 where 从 POST_ID 改成了 POST.POST_ID
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多