2013-06-12 189 views
-4

什麼與此查詢?: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'標題',LEFT('posts','p'at line 2

+3

既然你正在使用MySQL使用反引號而不是單引號圍繞表,列和別名。 – Taryn

+0

這是一個所謂的PICNIC錯誤。 –

回答

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 
+0

謝謝,但我得到了#1054 - '字段列表'中的未知列'posts.post_id' – ddacot

+0

那麼,表中是否有'post_id'列? –

4

您使用字符串文字作爲表:

FROM 'posts' 

如果您想逃跑的表名,使用反引號,如:

FROM `posts` 

逸出表名不是必需的; from posts是完全正常的。

1

我認爲,你的左邊的語法錯誤時,第一個逗號改爲一段

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

應該

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