简体   繁体   English

如何比较来自两个不同表SQL的数据

[英]How to compare data from two different tables SQL

This maybe simple but I'm not sure how to go about it. 这也许很简单,但是我不确定如何去做。 I have 2 tables Match and Players 我有2张桌子Match和Players

Players table
-------------
PlayerID     int
PlayerName   varchar(20)
TeamID       int
TeamName     varchar(10)

Match table
-----------
MatchID         int 
Team1           varchar(20)
Team2           varchar(20)
MatchDate       date

For example for a specific match I would like to list all player names from both teams. 例如,对于特定的比赛,我想列出两支球队的所有球员姓名。

Say 28/03/16 Liverpool vs Arsenal , how do I get the player names from the Players table? 比如说28/03/16 Liverpool vs Arsenal ,我该如何从“球员”表中获得球员名称?

Anything you could tell me will help. 您能告诉我的任何信息都会有所帮助。

Instead of storing team names as team1 and team2 in your match table, store their corresponding team ids. 不要在比赛表中将团队名称存储为team1和team2,而是存储其对应的团队ID。

Edit : Every match should unique match id, so that date filter is not required. 编辑:每个匹配项都应具有唯一的匹配ID,因此不需要日期过滤器。

This could help you to retrieve records using the query : 这可以帮助您使用查询检索记录:

select * from players a where exists(select 1 from match b where 
b.MATCH_ID= :match_id and (a.team_id=b.team1 OR
a.team_id =b.team2))

Get the row from match table. match表中获取行。 If you don't know if team1 is Liverpool or Arsenal, or vice versa for team2 如果您不知道team1是利物浦还是阿森纳,反之亦然

 SELECT m.matchid
   FROM match m
  WHERE m.date = TO_DATE('2016-03-28','YYYY-MM-DD')
    AND m.team1 IN ('Liverpool','Arsenal')
    AND m.team2 IN ('Liverpool','Arsenal')
    AND m.team1 <> m.team2

Next, make two copies of the row... 接下来,制作该行的两个副本...

 SELECT m.matchid
   FROM (SELECT 1 AS i UNION ALL SELECT 2) d
  CROSS
   JOIN match m
  WHERE m.date = TO_DATE('2016-03-28','YYYY-MM-DD')
    AND m.team1 IN ('Liverpool','Arsenal')
    AND m.team2 IN ('Liverpool','Arsenal')
    AND m.team1 <> m.team2

The perform join to the players table, looks like we use teamname column to match. 执行联接到玩家表,看起来就像我们使用teamname列进行匹配。

 SELECT CASE WHEN d.i = 1 THEN m.team1 ELSE m.team2 END AS teamname
      , p.playername
   FROM (SELECT 1 AS i UNION ALL SELECT 2) d
   JOIN match m
     ON m.date = TO_DATE('2016-03-28','YYYY-MM-DD')
    AND m.team1 IN ('Liverpool','Arsenal')
    AND m.team2 IN ('Liverpool','Arsenal')
    AND m.team1 <> m.team2
   LEFT
   JOIN players p
     ON p.teamname IN (m.team1, m.team2) 
  ORDER BY d.i, p.playerid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM