MySQL语法错误(完全是新的)

时间:2014-02-07 14:13:06

标签: mysql sql

当我运行以下查询时:

SELECT MONTHNAME( start_date_time ) AS
MONTH, SUM (
CASE WHEN YEAR( start_date_time ) = '2011' AND YEAR( u.registered) = '2011'
THEN oi.qty
END )
AS '2011', SUM (


CASE WHEN YEAR( start_date_time ) = '2012' AND YEAR( u.registered) = '2012'
THEN oi.qty
END )
AS '2012',  SUM (


CASE WHEN YEAR( start_date_time) = '2013' AND YEAR( u.registered) = '2013'
THEN oi.qty
END )
) AS '2013' 

FROM order_items oi INNER JOIN events e ON oi.eventid = e.eventid INNER JOIN company_campaign ON e.event_campaign_id = company_campaign.campaignid
     INNER JOIN company
          ON company.companyid = company_campaign.companyid
     INNER JOIN users u
          ON u.userID = company.createdby
WHERE start_date_time > '2011-01-01 00:00:00'
GROUP BY MONTH
ORDER BY MONTH( start_date_time ) ASC

我收到错误:

  

1064 - 您的SQL语法出错;查看与您的MySQL服务器版本相对应的手册,以便在''附近使用正确的语法'AS'2013'FROM order_items oi INNER JOIN events e ON oi.eventid = e.eventid'at line 18

我对SQL完全陌生,加入是我迄今为止取得的最大成就,但这完全让我感到难过。有时候我会使用错误的类型'但这是正确的。有时我也会在查询结束时放一个。我正在使用MySQL 5.5

2 个答案:

答案 0 :(得分:2)

看起来像是一个额外的右括号(就在AS 2013之前)引起这种情况。

尝试:

SELECT MONTHNAME( start_date_time ) AS
MONTH, 

SUM ( CASE WHEN YEAR( start_date_time ) = '2011' AND YEAR( u.registered ) = '2011'
THEN oi.qty END )
AS '2011', 

SUM ( CASE WHEN YEAR( start_date_time ) = '2012' AND YEAR( u.registered ) = '2012'
THEN oi.qty END )
AS '2012',  

SUM ( CASE WHEN YEAR( start_date_time) = '2013' AND YEAR( u.registered ) = '2013'
THEN oi.qty END )
AS '2013' 

FROM order_items oi INNER JOIN events e ON oi.eventid = e.eventid INNER JOIN company_campaign ON e.event_campaign_id = company_campaign.campaignid
     INNER JOIN company
          ON company.companyid = company_campaign.companyid
     INNER JOIN users u
          ON u.userID = company.createdby
WHERE start_date_time > '2011-01-01 00:00:00'
GROUP BY MONTH
ORDER BY MONTH( start_date_time ) ASC

答案 1 :(得分:1)

'As 2013'之前的额外关闭

  

)AS'2013'

删除它,它应该没问题。

只是添加 - 如果您将括号中的部分分开,它总是可以更轻松地阅读查询。花费更长的时间并添加更多行,但是当您将来再次使用它时,它会让其他人或自己更容易阅读(以及发现语法问题)。

e.g。这样写的很明显,问题出在哪里 -

SELECT 
MONTHNAME( start_date_time ) AS MONTH, 
SUM 
(
    CASE WHEN YEAR( start_date_time ) = '2011' AND YEAR( u.registered) = '2011'
    THEN oi.qty
    END 
) AS '2011', 
SUM 
(
    CASE WHEN YEAR( start_date_time ) = '2012' AND YEAR( u.registered) = '2012'
    THEN oi.qty
    END 
) AS '2012',  
SUM 
(
    CASE WHEN YEAR( start_date_time) = '2013' AND YEAR( u.registered) = '2013'
    THEN oi.qty
    END 
)
) AS '2013'