修复查询codeigniter模型语法错误中的错误

时间:2017-06-27 02:27:24

标签: mysql codeigniter model

为什么我在codeigniter中的模型中出现错误,其中显示:

A Database Error Occured
Error Number: 1064 
You have error in your SQL syntax;

当我尝试在mysql中运行它时工作正常。但是,当我把它放在我的CI模型中时,它给出了错误号码:1064

这是我的完整型号代码:

public function checkupID() {
        $query = $this->db->query(' SELECT check_up_id FROM tbl_check_up JOIN (SELECT MAX(CAST(SUBSTRING_INDEX(check_up_id, '-', -1) AS DECIMAL)) AS max_right FROM tbl_check_up) AS x
                    ON SUBSTRING_INDEX(check_up_id, '-', -1) = max_right ');
        return $query->result();
    }

我的表格结构

+-------------+----------+---------+--------+
|  Field      |  Type    |  NULL   | Key    |
+-------------+----------+---------+--------+
| check_up_id | varchar  |  NO     | PRI    |
+-------------+----------+---------+--------+
| note        | varchar  |  YES    |        |
+-------------+----------+---------+--------+

1 个答案:

答案 0 :(得分:1)

请在下面找到我的回答。您可以在mysql中创建存储过程,如下所示。

DELIMITER $$

DROP PROCEDURE IF EXISTS `getCheckUpId`$$

CREATE PROCEDURE `getCheckUpId`()
BEGIN
    SELECT 
        t1.check_up_id 
    FROM tbl_check_up t1 
    JOIN (SELECT MAX(CAST(SUBSTRING_INDEX(t2.check_up_id, '-', -1) AS DECIMAL)) AS max_right FROM tbl_check_up t2) AS x ON SUBSTRING_INDEX(t1.check_up_id, '-', -1) = x.max_right;
    END$$

DELIMITER ;

现在,您可以在模型中创建如下所述的内容。

public function checkupID() {
    $query = $this->db->query('call getCheckUpId()');
    return $query->row();
}

我希望这会对你有所帮助。如果它不起作用,请告诉我。