2012-06-06 49 views
3

我有一个查询一个问题,应该做到以下几点:MySQL的左连接相同的表和错误的结果

  1. 获取特定记录并计算他们的一些值的特定时期
  2. 计算相同的值这些关键字的另一段时间

这应该发生在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结果吗?

+0

+1'naughtymeetings'。 –

+0

你只用'JOIN'来试试它吗?我不认为你需要'LEFT JOIN'在这里。 –

回答

0

我想你需要INNER JOIN这里。尝试用INNER JOIN替换LEFT JOIN

P.S. 我不明白你想要什么,但我认为这个想法应该更简单。

(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 

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

+0

我尝试使用JOIN和INNER JOIN,但它不再工作。这里是我将尝试解释的屏幕截图:http://screencast.com/t/XpsiYlq6f – pocko

+0

也许尝试将这两个时间段的查询分开,就像我建议的那样。那么你可以很容易地发现错误。 –

+0

我试过这种方法,但是你提出的语法没有解决。我仍然在寻找一个类似的例子。 – pocko