简体   繁体   中英

Incorporating a join with a subquery into an existing query

I have a database that contains records for sports teams game stats and records, and I'm currently having an issue with figuring out how to retrieve the total points against a team over the season and incorporating it into a query that returns their total wins and losses.

The current query I have that does not show their points against is:

SELECT league_team_data.`Team Name` AS TeamName, league_team_data.TeamID, games.Result, count(*) AS Total, sum(case when games.`Result` = 'WIN' then 1 else 0 end) GamesWon, sum(case when games.`Result` = 'LOSS' then 1 else 0 end) GamesLost, sum(case when games.`Result` = 'WIN' then 2 when games.`Result` = 'TIE' then 1 else 0 end) Points, SUM(Score) PointsFor 
                FROM league_team_data

                LEFT JOIN games
                ON games.TeamID = league_team_data.TeamID

                INNER JOIN teams_in_divisions
                ON teams_in_divisions.DivisionID_FK = 2 AND games.TeamID = teams_in_divisions.TeamID_FK

                GROUP BY TeamID 
                ORDER BY PointsFor DESC, Points DESC

The '2' hard coded here is staying hardcoded as it works for it's purpose.

The query that returns their total points against is:

SELECT SUM(Score) FROM `games` WHERE TeamID <> 1 AND 
GameID IN (SELECT GameID FROM games WHERE TeamID = 1)

The '1' hardcoded here needs to be changed to work with the league_team_data.TeamID from the above query.

So, I need to incorporate the second query into the first, in order to add a column for 'Points Against', which is what the second query returns.

The 'games' table has this data (and more, but this is what is pertinent for this question):

GameID | TeamID | Score |
   1       3        20
   1       5        28

Each row is the game stats from a game for one of the teams involved in the game, so the 'Score' column is that teams score. So, in order to get the points against the team I need to sum the 'Score' column for all rows with a GameID that they played in, but not the score from their row but rather their opponents row. The second query accomplishes this.

Sorry if this is a really basic question (I feel like I'm missing something obvious!), but any help would be very much appreciated!

As requested, here are the create table statements:

Table league_team_data:

CREATE TABLE `league_team_data` (
`TeamID` mediumint(10) NOT NULL AUTO_INCREMENT,
`Team Name` varchar(50) DEFAULT NULL,
`Team Name Short` varchar(50) DEFAULT NULL,
`Team Name Initials` varchar(10) DEFAULT NULL,
`Team Background Image` varchar(100) DEFAULT NULL,
`Team Logo` varchar(100) DEFAULT NULL,
PRIMARY KEY (`TeamID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

Table games:

CREATE TABLE `games` (
`Game Date` date NOT NULL,
`GameTime` time NOT NULL,
`GameID` mediumint(10) NOT NULL,
`TeamID` mediumint(10) NOT NULL,
`Team` varchar(50) NOT NULL,
`Score` int(5) NOT NULL,
`Result` varchar(5) NOT NULL,
`Home Team` varchar(50) NOT NULL,
`HomeTeamID` mediumint(10) NOT NULL,
`Away Team` varchar(50) NOT NULL,
`AwayTeamID` mediumint(10) NOT NULL,
`Game Status` varchar(10) NOT NULL,
`SeasonID` int(10) NOT NULL,
PRIMARY KEY (`GameID`,`TeamID`),
CONSTRAINT `FK_gameid` FOREIGN KEY (`GameID`) REFERENCES `league_games` (`GameID`) ON  DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Table teams_in_divisions:

CREATE TABLE `teams_in_divisions` (
`DivisionID_FK` mediumint(10) NOT NULL,
`TeamID_FK` mediumint(10) NOT NULL,
UNIQUE KEY `DivisionID_TeamID` (`DivisionID_FK`,`TeamID_FK`),
KEY `TeamID_FK` (`TeamID_FK`),
CONSTRAINT `teams_in_divisions_ibfk_2` FOREIGN KEY (`TeamID_FK`) REFERENCES `league_team_data` (`TeamID`),
CONSTRAINT `teams_in_divisions_ibfk_1` FOREIGN KEY (`DivisionID_FK`) REFERENCES `league_divisions` (`DivisionID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

It turns out that there is a simple way to do what I was trying to do, though I'm not sure how optimized this sort of query is.

I simply needed to add the subquery directly into the original SELECT statement. Here's the final code:

SELECT league_team_data.`Team Name` AS TeamName, 
league_team_data.TeamID, games.Result, count(*) AS Total, 
sum(case when games.`Result` = 'WIN' then 1 else 0 end) GamesWon, 
sum(case when games.`Result` = 'LOSS' then 1 else 0 end) GamesLost, 
sum(case when games.`Result` = 'WIN' then 2 when games.`Result` = 'TIE' then 1 else 0 end) Points, 
SUM(Score) PointsFor, 
(SELECT SUM(Score) AS PointsAgainst FROM `games` WHERE TeamID <> league_team_data.TeamID AND GameID IN (SELECT GameID FROM games WHERE TeamID = league_team_data.TeamID)) AS PointsAgainst

FROM league_team_data 

LEFT JOIN games ON games.TeamID = league_team_data.TeamID 

INNER JOIN teams_in_divisions ON teams_in_divisions.DivisionID_FK = 1 AND games.TeamID = teams_in_divisions.TeamID_FK 

GROUP BY TeamID ORDER BY Points DESC

The part I added was the "SELECT SUM(Score) AS PointsAgainst..." line.

Again, this could be horribly inefficient, but it does work!

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.

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