-4

这个查询有什么问题?:

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

4

3 回答 3

4

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

FROM 'posts'

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

FROM `posts`

不需要转义表名;from posts很好。

于 2013-06-12T14:19:28.940 回答
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
于 2013-06-12T14:20:04.700 回答
1

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

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

应该

LEFT('posts'.'post_body', 512) AS 'preview',
于 2013-06-12T14:20:36.113 回答