如何计算不同时间的相同字段?

时间:2018-06-13 17:15:26

标签: mysql sql

我需要从我的数据库中提取特定玩家得分的所有目标。我有这个表设计:

MATCH

id | home | away | result | round_id

PLAYER

id | first_name | last_name

目标

match_id | player_marker_id | type

GOAL_TYPE

id | description

goal基本上包含match中得出的所有目标,该表将match_id字段绑定为FK的{​​{1}}。字段match.idplayer_marker_id FKplayer.id包含目标可以承担的所有类型,目标有4种状态:

goal_type

我需要做的是让topscorers玩家计算一个1: first_goal 2: goal 3: pg 4: og 的数量,我不需要返回first_goal, goal, pg因为对应og

我现在做了什么:

auto goal.

此查询有效,但未返回预期结果,实际上我得到:

$sql = $this->db->prepare("SELECT
p.first_name AS player_first_name,
p.last_name AS player_last_name,
COUNT(*) AS goal_scored,
p.id AS player_id
FROM `match` m
INNER JOIN goal g ON g.match_id = m.id
INNER JOIN player p ON g.player_marker_id = p.id
WHERE m.round_id = :round_id AND g.type != 4
GROUP BY p.id
ORDER BY goal_scored DESC, player_last_name DESC");

我会返回此输出:

{
    "player_first_name": "Ali",
    "player_last_name": "Sowe",
    "goal_scored": "21",
    "player_id": "246638"
},
{
    "player_first_name": "Sindrit",
    "player_last_name": "Guri",
    "goal_scored": "20",
    "player_id": "211786"
},

我也尝试过这样做:

 {
    "player_first_name": "Ali",
    "player_last_name": "Sowe",
    "goal_scored": "21",
    "player_id": "246638", 
    "first_goal": "19",
    "goal": "1",
    "pg": "1"
}

但这将返回:

  

SQLSTATE [42000]:语法错误或访问冲突:1055 SELECT列表的表达式#4不在GROUP BY子句中,并且包含非聚合列'swp.g.type',它在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by

不兼容

我觉得这不是正确的方法。

PS:round_id是比赛的联赛。

感谢先进的任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以通过将case语句移动到count聚合函数内来仅计算给定目标类型的记录。试试这个:

SELECT
p.first_name AS player_first_name,
p.last_name AS player_last_name,
COUNT(*) AS goal_scored,
COUNT(case when g.type = 1 then 1 else null end) as first_goal,
COUNT(case when g.type = 2 then 1 else null end) as goal,
COUNT(case when g.type = 3 then 1 else null end) as pg,
p.id AS player_id
FROM `match` m
INNER JOIN goal g ON g.match_id = m.id
INNER JOIN player p ON g.player_marker_id = p.id
WHERE m.round_id = :round_id AND g.type != 4
GROUP BY p.id
ORDER BY goal_scored DESC, player_last_name DESC 

答案 1 :(得分:0)

好吧,如果找不到更好的解决方案,可以随时使用TOP(在SQL Server中)或LIMIT(在MySQL中)来指定返回的结果数。我假设你的第一个解决方案中返回的第一条记录是正确的。以下是如何使用它们https://www.w3schools.com/sql/sql_top.asp

的链接