来自不同表的SQL行

时间:2012-05-18 20:46:43

标签: sql

我有两张表,我想要提供信息。第一个表的名称是Play,另一个是Game。

Player Game_ID Points

Game_ID Length Judged_by

我想编写一个只显示具有相同game_ID的玩家的SQL查询。还有那场比赛的长度。我对SQL很陌生,不知道如何做到这一点。

1 个答案:

答案 0 :(得分:4)

不太确定你想要什么。如果您希望所有玩过1场比赛的用户都使用:

select p.player, g.game_id, g.length 
from game g
inner join playing p on g.game_id = p.game_id
group by game_id
having count(game_id) > 1

如果你想让所有玩过特定游戏的玩家都使用(game_id就是一个例子):

select p.player, g.game_id, g.length 
from game g
inner join playing p on g.game_id = p.game_id
where game_id = 123

修改

你走了:

select p.player, g.game_id, g.length
from game g 
inner join playing p on g.game_id = p.game_id
where g.game_id in (  select g.game_id
                      from game g
                      inner join playing p on g.game_id = p.game_id
                      group by g.game_id
                      having count(p.game_id) > 1
                    )
order by g.game_id

请参阅此SQLFiddle example以确认其有效。

编辑2

我不知道playingplayers表之间的关系。我在此示例中使用了列idplayer来获取玩家名称:

select g.game_id, g.length, p.first_name, p.last_name
from game g 
inner join playing pg on g.game_id = pg.game_id
inner join Players p on p.id = pg.player
where g.game_id in (  select g.game_id
                      from game g
                      inner join playing pg on g.game_id = pg.game_id
                      group by g.game_id
                      having count(pg.game_id) > 1
                    )
order by g.game_id

上次修改:

select g.game_id, g.length, p.first_name, p.last_name, j.Judge_firstname, j.Judge_lastname
from game g 
inner join playing pg on g.game_id = pg.game_id
inner join Players p on p.id = pg.player
inner join judges j on j.judge_id = g.judged_by
where g.game_id in (  select g.game_id
                      from game g
                      inner join playing pg on g.game_id = pg.game_id
                      where play_date > to_date('2012-05-01', 'YYYY-MM-DD')
                      group by g.game_id
                      having count(pg.game_id) > 1
                    )
order by g.game_id

请参阅this example