mysql左连接同表求和错误结果

Posted

技术标签:

【中文标题】mysql左连接同表求和错误结果【英文标题】:Mysql left join same table sum wrong results 【发布时间】:2012-06-10 10:21:16 【问题描述】:

我对应该执行以下操作的查询有疑问:

    获取特定记录并计算它们在特定时间段内的一些值 计算这些关键字在另一个时间段内的相同值

这应该发生在 1 个查询中。我能够编写它,但 SUM() 返回的错误值远高于正常值。我认为这是因为 LEFT JOIN。

SELECT SQL_CALC_FOUND_ROWS table1.id, table1.KeywordId, table1.AccountName, table1.CampaignName, table1.AdGroupName, table1.Keyword, table1.MatchType, SUM(table1.Spend)/SUM(table1.Clicks) AS AverageCpc, SUM(table1.Impressions) AS Impressions, (SUM(table1.Clicks)*table1.revenue_price)/SUM(table1.Impressions) AS Ctr, SUM(table1.Impressions*table1.AveragePosition)/SUM(table1.Impressions) AS AveragePosition, SUM(table1.Clicks) AS Clicks, SUM(table1.Spend) AS Spend, SUM(table1.free_joins) AS FreeJoins, SUM(table1.paid_joins) AS PaidJoins, SUM(table1.paid_joins)*table1.revenue_price AS Revenue, (SUM(table1.paid_joins)*table1.revenue_price)-SUM(table1.Spend) AS Profit, (SUM(table1.paid_joins)*table1.revenue_price)/SUM(table1.Clicks) AS RevPerClick, table1.CurrentMaxCpc, SUM(table2.Impressions) AS Impressions_chg, SUM(table2.Clicks) AS Clicks_chg, SUM(table2.Impressions*table2.AveragePosition)/SUM(table2.Impressions) AS AveragePosition_chg, (SUM(table2.Clicks)*table2.revenue_price)/SUM(table2.Impressions) AS Ctr_chg, SUM(table2.Spend)/SUM(table2.Clicks) AS AverageCpc_chg, table2.CurrentMaxCpc as CurrentMaxCpc_chg, SUM(table2.free_joins) AS FreeJoins_chg, SUM(table2.paid_joins) AS PaidJoins_chg
            FROM keywords_stats_google_naughtymeetings as table1
            LEFT JOIN keywords_stats_google_naughtymeetings as table2
            ON table1.keywordId = table2.keywordId
            WHERE table1.timeperiod >= '2012-05-21 00:00:00' and table1.timeperiod <= '2012-05-27 00:00:00'
            AND table2.timeperiod >= '2012-05-14' and table2.timeperiod <= '2012-05-20'

            GROUP BY table1.KeywordId, table1.MatchType, table1.revenue_price, table2.KeywordId, table2.MatchType, table2.revenue_price
            ORDER BY  FreeJoins
                    asc
            LIMIT 0, 10

谁能给我一个建议,我怎样才能得到正确的 SUM 结果?

【问题讨论】:

您是否仅使用JOIN 尝试过?我认为您在这里不需要LEFT JOIN 【参考方案1】:

我认为你需要INNER JOIN。尝试将LEFT JOIN 替换为INNER JOIN

附: 我没有得到你想要的,但我认为这个想法应该更简单。

(SELECT id, fields_for_first_period_of_time
  FROM keywords_stats_google_naughtymeetings) t1
  JOIN
(SELECT id, fields_for_second_period_of_time
  FROM keywords_stats_google_naughtymeetings) t2
ON t1.id = t2.id

这只是这个想法的草图。我的意思是通过两个单独的查询获得结果。然后加入他们。这将更容易调试。我希望这可以帮助你。

【讨论】:

我尝试了 JOIN 和 INNER JOIN,但它不再工作了。这是我将尝试解释的屏幕截图:screencast.com/t/XpsiYlq6f 也许尝试将您的查询拆分为两个时间段,就像我建议的那样。你可以很容易地发现错误。 我试过这种方式,但你提出的语法没有奏效。我还在寻找类似的例子。

以上是关于mysql左连接同表求和错误结果的主要内容,如果未能解决你的问题,请参考以下文章

mysql左连接没有数据还会查出来吗

如何使用 MySQL 展平左连接的结果?

Mysql之左连接右连接内连接——示例 (转)

左连接的where子句中的Mysql查询错误

如何使用 group_concat 和左连接计算 mysql 查询的结果

mysql左连接查询结果不准确