如何在Join codeigniter中插入SELECT

时间:2015-03-20 14:06:25

标签: php codeigniter

如何在Codeigniter中的$this->join()中添加子查询选择? 我试过这样做:

 $this->db->join('stocks AS stn', 
 'stn.stocksIdMF = (SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE 
    b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
    ORDER BY stn.stocksId DESC LIMIT 1', 'LEFT');

完整查询:

 $this->db->from('medicalfacilities');
        $this->db->join('users', 'users.idUsers = medicalfacilities.MedicalFacilitiesIdUser');
        $this->db->join('medicalfacilities_directions', 'medicalfacilities_directions.id_MF = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
        $this->db->join('subscrubetousers su', 'su.SubscrubeToUsersIdNote = medicalfacilities.MedicalFacilitiesIdUser AND su.SubscrubeToUsersType = 9', 'LEFT');
        $this->db->join('thematicspecialization', 'thematicspecialization.idSpecialization = medicalfacilities_directions.id_specialization', 'LEFT');
        $this->db->join('evaluationinstitution ev', 'ev.evaluationinstitutionIdInst = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
        $this->db->join('stocks', 'stocks.stocksIdMF = medicalfacilities.MedicalFacilitiesIdUser AND stocks.stocksEndDate >= UNIX_TIMESTAMP()', 'LEFT');
        $this->db->join('commentstomedicalfacilities', 'commentstomedicalfacilities.CommentsToMedicalFacilitiesIdMedical = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
        $this->db->join('medicalfacilities_type', 'medicalfacilities_type.idMF = medicalfacilities.MedicalFacilitiesIdUser');
        $this->db->join('typesmedicalfacilities', 'typesmedicalfacilities.type = medicalfacilities_type.type');
        $this->db->join('stocks AS stn', 'stn.stocksIdMF = (SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
        ORDER BY stn.stocksId DESC LIMIT 1)', 'LEFT', FALSE);

上次JOIN做错了查询。

错误是:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE b.MedicalFacilitiesI' at line 12

2 个答案:

答案 0 :(得分:1)

FALSE的末尾添加->join()参数,如下所示:

$this->db->join('','','', FALSE)

答案 1 :(得分:1)

试试这个:

$this->db->join('stocks AS stn', 
 'stn.stocksIdMF = (SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE 
    b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
    ORDER BY stn.stocksId DESC LIMIT 1)', 'LEFT', FALSE);