我在匹配表中有以下数据:
5;{"Id":1,"Teams":[{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}],"TeamRank":[1,2]} 6;{"Id":2,2]}
我想选择每个最后一个不同的团队在他们的名字.即我想要一个返回的查询:
6;{"Name":"TeamA",{"Name":"BBB"} 6;{"Name":"TeamB",{"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';
但这返回:
06003
我明白Postgres doesn’t have equality for JSON.我只需要平等的球队名称(一个字符串),那个球队的球员不需要比较.
任何人都可以提出替代方法来做到这一点吗?
以供参考:
SELECT id,json_array_elements(match->'Teams') AS team FROM matches
收益:
5;"{"Name":"TeamA",{"Name":"BBB"}]}" 5;"{"Name":"TeamB",{"Name":"DDD"}]}" 6;"{"Name":"TeamA",{"Name":"BBB"}]}" 6;"{"Name":"TeamB",{"Name":"DDD"}]}"
编辑:我转换为文本,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可以去.有关:
> Query for element of array in JSON column
> Query for array elements inside JSON type
JSON和平等
在Postgres中没有json数据类型的等号运算符,但jsonb(Postgres 9.4)有一个: