SQL Query,试图提高效率(Oracle DBMS)

时间:2013-02-04 18:51:58

标签: sql performance oracle database

对于下表(我用**来表示主键的部分)

Team (*tid*, name)
Game (*gid*, tid, name, year)
Member (*mid*, name)
MemberOf (*mid*, *tid*, startyear, endyear, position)

我需要 显示每个前锋的历史(位置) 如果startyear为NULL,请使用该球员最早的比赛中该球员的年份 结果:前锋名称,球队名称,开始年份,结束年份 按Strikers名称排序,然后是开始年份

虽然我有一个解决方案,但我认为它不是很有效率 执行计划推断节点成本为28。 希望改进建议和解释吗?

1 个答案:

答案 0 :(得分:2)

您可以使用left outer joincoalesce通过一个查询执行此操作(如果我的逻辑正确):

SELECT Striker_Name, Team_Name, coalesce(MO.STARTYEAR, g.start_year), MO.ENDYEAR
FROM (SELECT NAME AS Striker_Name, MID
      FROM MEMBER
      ) ME JOIN
      (SELECT MID, TID, STARTYEAR AS Start_Year, ENDYEAR AS End_Year
       FROM MEMBEROF
       WHERE POSITION = 'striker'
      ) MO ON ME.MID = MO.MID left outer JOIN
      (SELECT NAME AS Team_Name, TID
       FROM TEAM
      ) T
      ON MO.TID = T.TID left outer JOIN
      (SELECT GID, MIN(GAME.YEAR) AS Start_Year FROM GAME GROUP BY TID
      ) G
      ON G.TID = MO.TID
ORDER BY Striker_Name, Start_Year

你似乎从最早的比赛开始填补了这一年。只需进行连接并在select中决定使用哪一个。