使用自联接的SQl查询

时间:2013-05-30 22:10:35

标签: mysql sql

我有一张看起来像这样的表

YR    Game
1960  football
1961  football
1962  football
1962  tennis
1963  football
1963  golf
1965  football
1965  tennis 
1965  golf
1967  tennis
1967  volleyball

如何使用join编写查询来查找必须将足球作为游戏而不是网球的年份..

3 个答案:

答案 0 :(得分:3)

您可以使用WHERE过滤器来获取结果:

select yr, game
from yt
where game = 'Football'
  and yr not in (select yr
                 from yt
                 where game = 'tennis');

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

您可以使用连接来过滤它(下方是您需要两列上的索引):

SELECT YR FROM table AS a
LEFT JOIN table AS b ON b.YR = a.YR AND b.Game = 'tennis'
WHERE a.Game = 'football' AND b.Game IS NULL

答案 2 :(得分:0)

也许这个查询?

select game_year from table_game a left outer join table_game b on a.game_year= 
b.game_year and b.game = 'tennis' where a.game = 'football' and coalesce(b.game, '') = ''