This maybe simple but I'm not sure how to go about it. I have 2 tables Match and 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?
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.
Edit : Every match should unique match id, so that date filter is not required.
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. If you don't know if team1 is Liverpool or Arsenal, or vice versa for team2
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.