我在匹配表中有以下数据:
5;{"Id":1,"Teams":[{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
6;{"Id":2,"Teams":[{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
我想按名称选择表格中最后一个不同的团队。即我想要一个将返回的查询:
6;{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}
6;{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}
所以上次该团队出现在表格中的每个团队。
我一直在使用以下内容(来自 here ):
WITH t AS (SELECT id, json_array_elements(match->'Teams') AS team FROM matches)
SELECT MAX(id) AS max_id, team FROM t GROUP BY team->'Name';
但这会返回:
ERROR: could not identify an equality operator for type json SQL state: 42883 Character: 1680
我了解 Postgres doesn't have equality for JSON .我只需要团队名称(字符串)相等,不需要比较该团队的球员。
谁能推荐一种替代方法来做到这一点?
供引用:
SELECT id, json_array_elements(match->'Teams') AS team FROM matches
返回:
5;"{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]}"
5;"{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}"
6;"{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]}"
6;"{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}"
编辑:我转换到text
并跟随this question ,我使用了 DISTINCT ON
而不是 GROUP BY
。这是我的完整查询:
WITH t AS (SELECT id, json_array_elements(match->'Teams') AS team
FROM matches ORDER BY id DESC)
SELECT DISTINCT ON (team->>'Name') id, team FROM t;
返回我上面想要的。有没有人有更好的解决方案?
最佳答案
LATERAL
连接更短、更快、更优雅:
SELECT DISTINCT ON (t.team->>'Name') t.team
FROM matches m, json_array_elements(m.match->'Teams') t(team);
ORDER BY t.team->>'Name', m.id DESC; -- to get the "last"
如果您只想要不同的团队,可以使用 ORDER BY
。相关:
JSON 和平等
在 Postgres 中没有用于 json
数据类型的相等运算符,但有一个用于 jsonb
(Postgres 9.4+) 的相等运算符:
关于sql - Postgres 中的 GROUP BY - JSON 数据类型不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30519458/