简体   繁体   English

如何告诉SQL使用另一个表作为输入值来运行命令?

[英]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 周|主队|客队|主场得分|客场得分|结果|比赛ID

Where Result can be either A (away win), H (home win), or D (draw). 结果可以是A(客场获胜),H(主场获胜)或D(平局)。 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

暂无
暂无

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

相关问题 如何在记事本中编写mysql程序,并可以使用Windows命令提示符运行它? 如果是,请告诉我如何完成 - How do I write a mysql program in Notepad, and can I run it using Windows Command Prompt? If yes, please tell me how it is done 如何编写SQL命令以使用同一表中另一列的数据来输入列? - How to write an SQL command to input a column by using data from another column in the same table? 如何使用PHP将一个SQL命令的返回值插入另一个表中 - How to insert return value of one SQL command into another table using PHP 如何根据另一个表中的值动态更新一个表中的sql列 - How do I dynamically update sql column in one table based on value in another table 如何将 SQL 记录中的一个字段的值更改为另一个表中的值? - How do I change the value of one field in SQL record to a value from another table? 如何根据另一个字符串的值获取表值? - How do I get a table value based on the value of another string? 使用PHP如何从数据库表中检索某个字段值,然后将该单个字段值输入到新表中 - Using PHP how do I retrieve a certain field value from a database table and then input that single field value into a new table 如何根据另一个选择的结果制作一个SQL表? - How do I make a SQL table from the result of another select? SQL-如何在另一个表中使用选定的ID? - SQL - How do i use a selected ID in another table? 如何从另一个表引用SQL? - How do I refer from another table for SQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM