0

我有下面的脚本在内部查询中引发错误。我使用 Sequel Pro 并且只收到此错误:

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

所以我不确定实际问题是什么。我尝试在内部查询中进行显式内部联接,以防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

4 回答 4

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'

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

于 2013-02-26T18:41:39.650 回答
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'
于 2013-02-26T18:37:24.310 回答
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。

于 2013-02-26T18:38:20.767 回答
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'
于 2013-02-26T18:39:11.573 回答