使用mysql DATE_FORMAT时出现语法错误

时间:2014-05-16 05:31:17

标签: php mysql

我正在将mysql DATE_FORMAT用于数据库中的特定日期时间。 Mysql查询是:

$this->db->select('remarks_date, DATE('remarks_date') AS rem_dateonly, DATE_FORMAT('remarks_date', '%y-%m-%d %h:%i') AS day_hour_mins, DATE_FORMAT('remarks_date', '%y-%m-%d %h') AS day_hour, tbl_complain_detail.complain_summary, tbl_complain_detail.id, tbl_complain_detail.complain_no, tbl_complain_detail.created_by, escalation_status, tbl_admin_user.first_name, tbl_admin_user.middle_name, tbl_admin_user.last_name');
$this->db->where('tbl_complain_remarks.status', 'Time Extension');
$this->db->where('tbl_complain_detail.status !=', 'Completed');
$this->db->where('tbl_complain_detail.time_extension_status', '1');
$this->db->join('tbl_complain_remarks', 'tbl_complain_remarks.complain_id = tbl_complain_detail.id');
$this->db->join('tbl_admin_user', 'tbl_admin_user.id = tbl_complain_detail.user_id');
$result2 = $this->db->get('tbl_complain_detail')->result();

这里我收到错误

PHP Parse error: syntax error, unexpected T_STRING in select line

并且它没有接受%。为什么呢?

我做错了吗?任何帮助/建议将不胜感激。

3 个答案:

答案 0 :(得分:5)

您的问题在于表格中的别名。要在表中使用别名,请使用``符号。试试这个吧。

SELECT remarks_date AS rem_date_only, DATE_FORMAT(remarks_date, "%Y-%m-%d %H:%i") AS `day_hour_mins`, DATE_FORMAT(remarks_date, "%Y-%m-%d %H") AS `day_hour`, tbl_complain_detail.complain_summary, tbl_complain_detail.id, tbl_complain_detail.complain_no, tbl_complain_detail.created_by, escalation_status, tbl_admin_user.first_name, tbl_admin_user.middle_name, tbl_admin_user.last_name
FROM (`tbl_complain_detail`)
JOIN `tbl_complain_remarks` ON `tbl_complain_remarks`.`complain_id` = `tbl_complain_detail`.`id`
JOIN `tbl_admin_user` ON `tbl_admin_user`.`id` = `tbl_complain_detail`.`user_id`
WHERE `tbl_complain_remarks`.`status` =  'Time Extension'
AND `tbl_complain_detail`.`status` != 'Completed'
AND `tbl_complain_detail`.`time_extension_status` =  '1'

答案 1 :(得分:2)

您使用简单字符串的单引号。对复杂字符串使用双引号。

$this->db->select("remarks_date, DATE(remarks_date) AS rem_dateonly, DATE_FORMAT(remarks_date, '%y-%m-%d %h:%i') AS day_hour_mins, DATE_FORMAT(remarks_date, '%y-%m-%d %h') AS day_hour, tbl_complain_detail.complain_summary, tbl_complain_detail.id, tbl_complain_detail.complain_no, tbl_complain_detail.created_by, escalation_status, tbl_admin_user.first_name, tbl_admin_user.middle_name, tbl_admin_user.last_name", false);

答案 2 :(得分:0)

在select query中指定列时,Mysql不支持'单引号,因此请使用此

DATE(`remarks_date`)

OR

DATE(remarks_date)

而不是

DATE('remarks_date')

$this->db->select('remarks_date, DATE(`remarks_date`) AS rem_dateonly, DATE_FORMAT(`remarks_date`, "%y-%m-%d %h:%i") AS day_hour_mins, DATE_FORMAT(`remarks_date`, "%y-%m-%d %h") AS day_hour, tbl_complain_detail.complain_summary, tbl_complain_detail.id, tbl_complain_detail.complain_no, tbl_complain_detail.created_by, escalation_status, tbl_admin_user.first_name, tbl_admin_user.middle_name, tbl_admin_user.last_name');