简体   繁体   中英

How do I tell SQL to run a command using another table as the input value?

I'm trying to build a query that will show me the number of points for each team (as a start anyway) in my database. I have two tables, one with the list of teams, and one with the matches, in the format

Week|HomeTeam|AwayTeam|HomeScore|AwayScore|Result|MatchID

Where Result can be either A (away win), H (home win), or D (draw). I can find the number of points for a given team easily enough with

SELECT
(SELECT COUNT(matches.Result)*3 FROM matches WHERE (HomeTeam='Arsenal' AND Result='H') OR (AwayTeam='Arsenal' AND Result='A')) +
(SELECT COUNT(matches.Result) FROM matches WHERE (HomeTeam='Arsenal' OR AwayTeam='Arsenal') AND Result='D');

I want to do is something like:

FOR EACH teams.Team in teams
SELECT
(SELECT COUNT(matches.Result)*3 FROM matches WHERE (HomeTeam=Team AND Result='H') OR (AwayTeam=Team AND Result='A')) +
(SELECT COUNT(matches.Result) FROM matches WHERE (HomeTeam=Team OR AwayTeam=Team) AND Result='D');

Unfortunately, this isn't working and I can't quite figure out why. What am I doing wrong?

Simple use a subquery:

SELECT teams.Team,
((SELECT COUNT(matches.Result)*3 FROM matches WHERE (HomeTeam=teams.Team AND Result='H') OR (AwayTeam=Team AND Result='A')) +
(SELECT COUNT(matches.Result) FROM matches WHERE (HomeTeam=teams.Team OR AwayTeam=teams.Team) AND Result='D')) as Points

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