MySQL查询无法正常工作

时间:2012-08-09 08:03:42

标签: php mysql sql select

错误在哪里?

谢谢!

SELECT Table.id,
       Table.name,
   Table.kommentar,
   Table.pictureurl

   WHERE Table.news_id = 5, //without this line the query works!

   COUNT( Table1.comment_id ) AS numComments
   FROM DATABASE.news_comments          AS Table
   LEFT JOIN DATABASE.news_comments_comments AS Table1
   ON Table1.comment_id = Table.id

   GROUP BY Table.id
   ORDER BY Table.id DESC LIMIT 0,50

2 个答案:

答案 0 :(得分:5)

WHERE子句应该在FROM子句之后

SELECT `Table`.id,
       `Table`.name,
       `Table`.kommentar,
       `Table`.pictureurl,
       COUNT( Table1.comment_id ) AS numComments
FROM   DATABASE.news_comments          AS `Table`
          LEFT JOIN DATABASE.news_comments_comments AS Table1
             ON Table1.comment_id = `Table`.id
WHERE `Table`.news_id = 5    // <=== HERE
GROUP BY `Table`.id
ORDER BY `Table`.id DESC LIMIT 0,50

还有一件事,Table的别名应该用反引号转义,因为它是 Reserved Keyword in MySQL

答案 1 :(得分:0)

SELECT Table.id,
       Table.name,
   Table.kommentar,
   Table.pictureurl,   
   COUNT( Table1.comment_id ) AS numComments
   FROM DATABASE.news_comments  AS Table
   LEFT JOIN DATABASE.news_comments_comments AS Table1
   ON Table1.comment_id = Table.id

WHERE Table.news_id = 5   //===> where should be here

   GROUP BY Table.id
   ORDER BY Table.id DESC LIMIT 0,50