选择已购买指定游戏的人购买的所有游戏名称的列表

时间:2019-06-16 21:24:08

标签: sql

我要选择购买“ this_game”的玩家购买的游戏列表

这是我的3张桌子的基础:

PLAYERS(IDP INT PK, PSEUDO VARCHAR)
GAMES(IDG INT PK, TITLE VARCHAR)
SALES(IDP INT FK, IDG INT FK)

我已经尝试过类似的方法,但这是不正确的:

SELECT TITLE from SALES
JOIN GAMES on SALES.IDG = GAMES.IDG
JOIN PLAYERS on SALES.IDP = PLAYERS.IDP
GROUP BY TITLE
HAVING TITLE= 'this_game'

我尝试了不同的方法,但是没有一个起作用。

2 个答案:

答案 0 :(得分:0)

对所有3个表进行联接:

select distinct g.title
from games g
inner join sales s on s.idg = g.idg
inner join players p on p.idp = s.idp
where p.idp in (
  select s.idp 
  from sales s inner join games g
  on g.idg = s.idg 
  where g.title = 'this_game'
)

答案 1 :(得分:0)

您不需要players表来解决此问题,也不需要子查询,尽管这不是问题:

select distinct g2.title
from games g1 join
     sales s1
     on g1.idg = s1.idg and
        g1.title = 'this game' join
     sales s2
     on s1.idp = s2.idp join  -- same person
     games g2
     on g2.idg = s2.idg;