我正在尝试返回与已加入记录关联的GROUP_CONCAT
5个匹配项,我尝试按以下方式设置查询:
$sql = $this->db->prepare("SELECT l.*,
t.name as team_name,
r.name AS rank_name,
r.color AS rank_color,
GROUP_CONCAT(DISTINCT m.* LIMIT 5, ORDER BY m.id) AS last_five_matches,
FROM league_ranking l
LEFT JOIN team t ON l.team_id = t.id
LEFT JOIN competition_ranks r ON l.rank = r.id
LEFT JOIN `match` m ON m.home_team_id = l.team_id OR m.away_team_id = l.team_id
WHERE l.round_id = :round_id AND m.status = 5");
你可以看到我想要返回状态= 5的5场比赛。
我得到的问题是:
SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在'* LIMIT 5,ORDER BY m.id)附近使用正确的语法AS last_five_matches, 来自league_ranking l
我不明白GROUP_CONCAT
上的问题出在哪里,请注意,如果我删除GROUP_CONCAT
查询有效,是否有任何帮助?
更新
这是编辑的查询:
"SELECT l.*,
t.name as team_name,
r.name AS rank_name,
r.color AS rank_color,
GROUP_CONCAT(DISTINCT m.id ORDER BY m.id) AS last_five_matches
FROM league_ranking l
LEFT JOIN team t ON l.team_id = t.id
LEFT JOIN competition_ranks r ON l.rank = r.id
LEFT JOIN `match` m ON m.home_team_id = l.team_id OR m.away_team_id = l.team_id
WHERE l.round_id = :round_id AND m.status = 5
GROUP BY team_name"
我得到了:
语法错误或访问冲突:1055 SELECT列表的表达式#1不在GROUP BY子句中,并且包含非聚合列'swp.l.position',它在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by
不兼容
答案 0 :(得分:0)
根据the mysql documentation,您无法将LIMIT
语句与GROUP_CONCAT()
一起使用。试试这个:
.. GROUP_CONCAT(DISTINCT m.id, ORDER BY m.id) AS last_five_matches ..
答案 1 :(得分:0)
GROUP_CONTACT是Aggregation Operation,你需要有一个GROUP BY子句描述你在哪些值下聚合记录
SELECT l.*,
t.name as team_name,
r.name AS rank_name,
r.color AS rank_color,
GROUP_CONCAT(DISTINCT m.<column_name> LIMIT 5, ORDER BY m.id) AS last_five_matches,
FROM league_ranking l
LEFT JOIN team t ON l.team_id = t.id
LEFT JOIN competition_ranks r ON l.rank = r.id
LEFT JOIN `match` m ON m.home_team_id = l.team_id OR m.away_team_id = l.team_id
WHERE l.round_id = :round_id AND m.status = 5
GROUP BY team_name, rank_name, rank_color
答案 2 :(得分:0)
我相信你想要:
SELECT t.name as team_name, r.name AS rank_name, r.color AS rank_color,
SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT m.id ORDER BY m.id), ',', 5) AS last_five_matches
FROM team t LEFT JOIN
league_ranking l
ON l.team_id = t.id LEFT JOIN
competition_ranks r
ON l.rank = r.id LEFT JOIN
`match` m
ON m.home_team_id = l.team_id OR m.away_team_id = l.team_id
WHERE l.round_id = :round_id AND m.status = 5
GROUP BY t.name, r.name, r.color;
注意:
GROUP BY
个密钥与SELECT
中的未聚合列完全匹配。l.*
。它在GROUP BY
查询中没有意义。GROUP_CONCAT()
不支持LIMIT
。听起来不错,但它并不存在。相反,形成列表然后采取前5个元素。JOIN
订单更改为以team
开头。您似乎希望每个团队占一行,因此应该是FROM
。