从连接表中获取数据

时间:2018-06-01 07:31:05

标签: sql database oracle

我有两张这样的桌子。

create table teams (
  "ID" Integer NOT NULL ,
  "STADIUM_ID" Integer NOT NULL ,
  "NAME" Varchar2 (50) NOT NULL ,
    primary key ("ID") 
    ) ;

create table matches (
  "ID" Integer NOT NULL ,
  "HOMETEAM_ID" Integer NOT NULL ,
  "OPPONENT_ID" Integer NOT NULL ,
  "HOMESCORE" Integer,
  "OPPONENTSCORE" Integer,
primary key ("ID","HOME_ID","OPPONENT_ID") 
) ;

他们有以下数据:

select * from matches;

ID      HOME_ID OPPONENT_ID HOMESCORE OPPONENTSCORE
 1          5           2           5             2
 2          4           5           1             0
 3          3           2           1             0
 4          3           2           1             0
 5          1           2           2             0
 6          3           1           2             1

select * from teams;

ID     STADIUM_ID    NAME
 1          1        Team1
 2          3        Team2
 3          4        Team3
 4          2        Team4
 5          5        Team5

我需要让在主场输掉比赛的球队(与获胜者一样的球场冠军)。真的很高兴你的帮助...... 预期结果 - 没有这个数据,因为每个团队都有自己的体育场。

某些查询不起作用,但会显示我想要的内容。

select op.name from matches, (select name, stadium_id from teams where id = matches.home_id) home, (select name, stadium_id from teams where id = matches.opponent_id) op where home.stadium_id = op.stadium_id;

这个查询有两个问题 - 我没有比较得分让队伍丢失,我不能在这样的子查询中访问匹配。

3 个答案:

答案 0 :(得分:2)

试试这个解决方案:

select m.*,h.NAME as Home,o.NAME as Opponent from matches as m
Join teams h on h.STADIUM_ID = m.HOMETEAM_ID
Join teams o on o.STADIUM_ID = m.OPPONENT_ID
where m.HOMESCORE < m.OPPONENTSCORE

答案 1 :(得分:0)

你想要在家里迷路的球队。伪代码:select from teams where team in (set of home match losers)

select *
from teams
where id in
(
  select hometeam_id
  from matches
  where homescore < opponentscore
);

答案 2 :(得分:0)

如果您只想要在家中至少丢失一场比赛的所有球队的列表,则可以使用此查询。它处理了两支球队未来可以再次参赛的事实。

SELECT DISTINCT teams.stadium_id, teams.name
FROM matches
INNER JOIN teams ON (matches.home_id = teams.stadium_id)
WHERE matches.homescore < matches.opponentscore