如何获取上次相关更新和第二次相关更新

时间:2014-03-20 13:21:38

标签: mysql sql sugarcrm

我有3张牌桌:opportunitiestr_opportunity_updates
opportunities_tr_opportunity_updates_1_c。后者将opportunitiesopportunity_updates联系起来。

我想获得3列,第一列是机会名称,第二列是对机会进行的最后更新,第三列是对机会进行的第二次更新。

我想获得以下输出:

  -----------------------------------------------
  Opportunity | Last_Update | Second_Last update 
  -----------------------------------------------
  Opp1        | update      | second bla bla     
  -----------------------------------------------
  Opp2        | Lastest up. | second bla bla     

我有一个获取商机名称和最后更新的查询,但我不知道如何获得第二次更新,并将其作为另一列添加。这是一个子查询吗?如果是这样的话:

  SELECT opportunities.name AS Opportunity, tr_opportunity_updates.description AS Last_Update
  FROM opportunities
  LEFT JOIN opportunities_tr_opportunity_updates_1_c ON opportunities_tr_opportunity_updates_1_c.opportunities_tr_opportunity_updates_1opportunities_ida = opportunities.id
  LEFT JOIN tr_opportunity_updates ON opportunities_tr_opportunity_updates_1_c.opportunities_tr_opportunity_updates_1tr_opportunity_updates_idb = tr_opportunity_updates.id
  WHERE opportunities.deleted = 0
  GROUP BY opportunities.name
  LIMIT 0 , 30

我试图为此实现一个sql小提琴,但是我的表格和数据都很大,有许多不敬的字段,但除了date_created之外,所有与上述问题相关的信息除了所有表中的date_created之外都可能需要获取第二次更新?

1 个答案:

答案 0 :(得分:0)

由于没有人试图提供帮助,我会发布自己的答案:

 SELECT oppa.name AS Opportunity, tr_opportunity_updates.description AS Last_Update,
 (SELECT tou.description FROM opportunities oppb
 LEFT JOIN opportunities_tr_opportunity_updates_1_c ON opportunities_tr_opportunity_updates_1_c.opportunities_tr_opportunity_updates_1opportunities_ida = oppb.id LEFT JOIN tr_opportunity_updates tou ON opportunities_tr_opportunity_updates_1_c.opportunities_tr_opportunity_updates_1tr_opportunity_updates_idb = tou.id
 WHERE oppb.deleted =0 AND tou.deleted =0 AND oppb.id = oppa.id
 ORDER BY tou.date_modified Desc LIMIT 1,1) AS Second_Last_Update
 FROM opportunities oppa
 LEFT JOIN opportunities_tr_opportunity_updates_1_c ON opportunities_tr_opportunity_updates_1_c.opportunities_tr_opportunity_updates_1opportunities_ida = oppa.id
 LEFT JOIN tr_opportunity_updates ON opportunities_tr_opportunity_updates_1_c.opportunities_tr_opportunity_updates_1tr_opportunity_updates_idb = tr_opportunity_updates.id
 WHERE oppa.deleted =0 AND tr_opportunity_updates.deleted =0
  GROUP BY oppa.name