SQL语法查询错误

时间:2013-06-12 14:18:11

标签: mysql sql

此查询有什么问题?:

SELECT
    'posts'.'post_id' AS 'id',
    'posts'.'post_title' AS 'title',
    LEFT('posts','post_body', 512) AS 'preview',
    'posts'.'post_user' AS 'user',
    DATE_FORMAT('posts'.'post_date', '%d/%m/%Y %H:%i:%s') AS 'DATE',
    'comments'.'total_comments',
    DATE_FORMAT('comments'.'last_comment', '%d/%m/%Y %H:%i:%s') AS 'last_comment'
    FROM 'posts'
    LEFT JOIN (
        SELECT
        'post_id',
        COUNT('comment_id') AS 'total_comments',
        MAX('comment_date') AS 'last_comment'
        FROM 'comments'
        GROUP BY 'post_id'
    ) AS 'comments'
    ON 'posts'.'post_id' = 'comments'.'post_id'
    ORDER BY 'posts'.'post_date' DESC

我明白了:

  

#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在'.'post_id'AS'id','posts'附近使用正确的语法.'post_title'AS'title',LEFT('posts','p'at line 2

3 个答案:

答案 0 :(得分:4)

您正在使用字符串文字作为表格:

FROM 'posts'

如果您想要转义表名,请使用反引号,例如:

FROM `posts`

不需要转义表名; from posts完全没问题。

答案 1 :(得分:1)

不要使用普通撇号(“'”),而是在MYSQL中反复使用“`”。普通撇号用于引用字符串。还请注意我在

中更改了逗号
LEFT(`posts`,`post_body`, 512) as `preview`

到一段时间。

应该是:

SELECT
        `posts`.`post_id` AS `id`,
        `posts`.`post_title` AS `title`,
        LEFT(`posts`.`post_body`, 512) AS `preview`,
        `posts`.`post_user` AS `user`,
        DATE_FORMAT(`posts`.`post_date`, '%d/%m/%Y %H:%i:%s') AS `DATE`,
        `comments`.`total_comments`,
        DATE_FORMAT(`comments`.`last_comment`, '%d/%m/%Y %H:%i:%s') AS `last_comment`
        FROM `posts`
        LEFT JOIN (
            SELECT
                `post_id`,
                COUNT(`comment_id`) AS `total_comments`,
                MAX(`comment_date`) AS `last_comment`
                FROM `comments`
                GROUP BY `post_id`
                ) AS `comments`
        ON `posts`.`post_id` = `comments`.`post_id`
        ORDER BY `posts`.`post_date` DESC

答案 2 :(得分:1)

我认为您的LEFT语法错误,将第一个逗号更改为句号

LEFT('posts','post_body', 512) AS 'preview',

应该是

LEFT('posts'.'post_body', 512) AS 'preview',
相关问题