我有以下数据库表:
+----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+----------------+
| results_id | int(11) | NO | PRI | NULL | auto_increment |
| community_id | int(11) | NO | | NULL | |
| player1_id | int(11) | NO | | NULL | |
| player1_name | varchar(50) | NO | | NULL | |
| player1_team | varchar(50) | NO | | NULL | |
| player1_goals | int(11) | NO | | NULL | |
| player1_result | varchar(3) | NO | | NULL | |
| player2_goals | int(11) | NO | | NULL | |
| player2_result | varchar(3) | NO | | NULL | |
| player2_id | int(11) | NO | | NULL | |
| player2_name | varchar(50) | NO | | NULL | |
| player2_team | varchar(50) | NO | | NULL | |
| player1_pts | int(11) | NO | | NULL | |
| player2_pts | int(11) | NO | | NULL | |
| date | date | NO | | NULL | |
+----------------+-------------+------+-----+---------+----------------+
我想运行一个MySQL查询,告诉我一名球员的进球数最多。
该玩家可以是player1或player2。
我想它是这样的:
select member, goals, count(*) Total
from
(
select player2_name as member, player1_goals as goals
from results
WHERE player1_id = 2
union all
select player1_name as member, player2_goals as goals
from results
WHERE player2_id = 2
) AS T
group by goals
order by Total desc
Limit 1
这给出了一个结果:
member | goals | Total
Jamie Charles | 2 | 11
Jamie Charles | 0 | 8
Jamie Charles | 3 | 5
Jamie Charles | 1 | 4
Jamie Charles | 5 | 1
但看起来它说有多少目标已经发生。所以正确的结果是(2x11)+(3*5)+(1*4)+(5*1)
此查询的正确语法是什么?
答案 0 :(得分:1)
您需要按成员分组,使用sum
聚合函数来获取所有目标的总和。您不需要订单
select member, sum(goals), count(*) Total_goal_records
from
(
select player2_name as member, player1_goals as goals
from results
WHERE player1_id = 2
union all
select player1_name as member, player2_goals as goals
from results
WHERE player2_id = 2
) AS T
group by member
order by Total desc;