未知的内部查询错误

时间:2013-02-26 18:34:28

标签: mysql sql database

我有下面的脚本在内部查询上抛出错误。我使用Sequel Pro,我只得到这个错误:

  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在'SELECT Savings附近使用正确的语法   来自OfferSuggestionHeader osh   LEFT JOIN项目p   ON osh.OfferI'在第2行

所以我不确定实际问题是什么。我尝试在内部查询中进行显式内连接,以防p别名未被正确引用/解释或类似,但没有任何正面影响。

SELECT SUM(osh.Savings) as YTD, 
   SUM (SELECT Savings
FROM OfferSuggestionHeader osh
LEFT JOIN Projects p
ON osh.OfferID = p.offer_id
WHERE p.uid = 1 AND p.current_status < 3) 
   AS "Open Savings"
FROM OfferSuggestionHeader osh
LEFT JOIN Projects p
    ON p.offer_id = osh.OfferID
WHERE p.uid = '1'

感谢任何帮助。最好,

4 个答案:

答案 0 :(得分:1)

你不能总和(选择....)。

试试这个

 SELECT SUM(osh.Savings) as YTD, 
       (SELECT SUM(Savings)
       FROM OfferSuggestionHeader osh
       LEFT JOIN Projects p
       ON osh.OfferID = p.offer_id
       WHERE p.uid = 1 AND p.current_status < 3) 
 AS "Open Savings"
 FROM OfferSuggestionHeader osh
 LEFT JOIN Projects p
 ON p.offer_id = osh.OfferID
 WHERE p.uid = '1'

答案 1 :(得分:1)

似乎可以使用CASE简化:

SELECT SUM(osh.Savings) as YTD, 
   SUM (CASE WHEN p.current_status < 3 THEN Savings ELSE 0 END) AS "Open Savings"
FROM OfferSuggestionHeader osh
    INNER JOIN Projects p
        ON osh.OfferID = p.offer_id
WHERE p.uid = 1

此外,由于您将结果限制为p.uid = 1,因此不需要`LEFT JOIN。

答案 2 :(得分:1)

问题是你在SELECT上做SUM而不是反之亦然。 这应该有效:

SELECT SUM(osh.Savings) as YTD, 
    (SELECT SUM(Savings)
FROM OfferSuggestionHeader osh
LEFT JOIN Projects p
ON osh.OfferID = p.offer_id
WHERE p.uid = 1 AND p.current_status < 3) 
   AS "Open Savings"
FROM OfferSuggestionHeader osh
LEFT JOIN Projects p
    ON p.offer_id = osh.OfferID
WHERE p.uid = '1'

答案 3 :(得分:1)

我认为您可以更简单地将查询编写为:

SELECT SUM(osh.Savings) as YTD,
       SUM(case when p.current_status < 3 then Savings end) AS "Open Savings"
FROM OfferSuggestionHeader osh LEFT JOIN
     Projects p
     ON p.offer_id = osh.OfferID
WHERE p.uid = '1'

也就是说,您可以使用条件求和完全替换子查询。