2

For the following tables (I've used ** to indicate the parts of the primary keys)

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

I need to Show The History of each Striker (position) If startyear is NULL use the year from the earliest game for that player for that team Result: Striker Name, Team Name, Start Year, End Year Sorted by the Strikers name, then the start year

Whilst I have a solution I dont think it very efficient The Execution plan on infers a node cost of 28. Was Hoping for improvement suggestions and explanations?

3
  • Have you tried UNION ALL? Those look like mutually exclusive queries to me and UNION ALL doesn't try to filter out duplicates. Of course make sure that UNION ALL returns exactly the same results. Commented Feb 4, 2013 at 19:01
  • I don't see any fields that would enable me to find the year of the earliest game for a specific team. Does your game table have a date field that you are not displaying? Commented Feb 4, 2013 at 19:14
  • Thanks HLGEM, The ALL saved one on the Node Cost Dan, Your right, I missed it! Edited to add in Commented Feb 4, 2013 at 20:09

1 Answer 1

2

You can do this with one query, using left outer join and coalesce (if I have the logic correct):

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

You seem to be filling in the start year from the earliest game. Just do the join and decide in the select which one to use.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, it appears to be close to what I am after, however this seems to only return the results where STARTYEAR is NULL?
@user2036256 . . . I think I missed one of the joins. They should all be left outer joins.
The only other join is the first one. Changing it to a left outer just causes all Members to be listed!
@user2036256 . . . Duh. That condition was in the subquery. Silly mistake. The whole purpose of using one query was to get rid of that condition (as I just did).
Ahh, crap, Can't believe I didnt spot that either. Thanks! Havn't seen coalesce before. I think i need to take a few more sql tutorials

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.