内连接上的MYSQL语法错误

时间:2012-05-03 07:03:49

标签: mysql syntax

我得到这个错误 - 在'int inner join categories附近使用正确的语法作为cat on int.categoryID = cat.categoryID GRO'在第5行

我的sql -

SELECT interest_desc, categoryID, category_desc, MAX(num_in_cat) AS num_in_cat 
    FROM
    (
       SELECT int.interest_desc, int.category_ID, cat.category_desc, 
              COUNT(categoryID) AS num_in_cat
       FROM 
          interests as int 
          inner join categories as cat 
             on int.categoryID = cat.categoryID

       GROUP BY int.interest_desc, int.categoryID
     ) subsel 
     GROUP BY interest_desc, categoryID"

由于

3 个答案:

答案 0 :(得分:1)

您需要反引用int,因为它们是保留的关键字。

或者,使用其他别名。

SELECT interest_desc, categoryID, category_desc, MAX(num_in_cat) AS num_in_cat  
FROM 
( 
   SELECT `int`.interest_desc, `int`.category_ID, cat.category_desc,  
          COUNT(categoryID) AS num_in_cat 
   FROM  
      interests as `int`  
      inner join categories as cat  
         on `int`.categoryID = cat.categoryID 

   GROUP BY `int`.interest_desc, `int`.categoryID 
 ) subsel  
 GROUP BY interest_desc, categoryID" 

答案 1 :(得分:1)

interests表使用不同的别名。

另外 - 你需要理清以下内容:

  • categoryID vs category_ID - 哪一个是正确的?
  • count(categoryID)含糊不清,因为categoryIDcategories表格中都存在interests

假设两个表上的列都是categoryID,则以下内容应该有效:

SELECT interest_desc, categoryID, category_desc, MAX(num_in_cat) AS num_in_cat 
    FROM
    (
       SELECT intr.interest_desc, intr.categoryID, cat.category_desc, COUNT(cat.categoryID) AS num_in_cat
       FROM interests as intr inner join categories as cat on 
intr.categoryID = cat.categoryID
       GROUP BY intr.interest_desc, intr.categoryID
     ) subsel 
     GROUP BY interest_desc, categoryID;

答案 2 :(得分:0)

命名表int是个问题。它可以通过引用表名来解决,但你真的应该重命名它。为了你的理智,以及那些将在你之后工作的人。