0
我在加盟Postgres的一個JSON清單問題9.4Postgres的加入JSON名單
這裏是我的問題:
表結構:
CREATE TABLE players
(
id serial NOT NULL,
player json,
CONSTRAINT players_pkey PRIMARY KEY (id)
)
CREATE TABLE matches
(
id serial NOT NULL,
match json,
CONSTRAINT matches_pkey PRIMARY KEY (id)
)
樣本數據:
players
1;"{"Name":"AAA","Height":186,"Weight":65}"
2;"{"Name":"BBB","Height":195,"Weight":85}"
3;"{"Name":"CCC","Height":175,"Weight":72}"
4;"{"Name":"DDD","Height":168,"Weight":56}"
matches
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]}
每支球隊的球員都是球隊上一場比賽中的球員。一種越來越球隊名稱和球員(目前球隊)的列表查詢如下:
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
這將返回以下(隊表):
"{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]}"
"{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}"
我想參加每一個玩家與它們在列表中身高和體重以上的結果,這樣的輸出如下:
"{"Name":"TeamA","Players":[{"Name":"CCC","Height":175,"Weight":72},{"Name":"BBB","Height":195,"Weight":85}]}"
"{"Name":"TeamB","Players":[{"Name":"AAA","Height":186,"Weight":65},{"Name":"DDD","Height":168,"Weight":56}]}"
我試圖做到這一點使用INNER JOIN:
WITH u AS (SELECT DISTINCT ON (t.team->>'Name') t.team
FROM matches m, json_array_elements(m.match->'Teams') t(team) -- FROM ABOVE!!!
ORDER BY t.team->>'Name', m.id DESC)
SELECT player FROM (SELECT json_array_elements(team->'Players') FROM u) AS v
INNER JOIN players on v->>'Name'=player->>'Name';
這是對我想要的東西了一步,但我得到以下錯誤:
ERROR: operator does not exist: record ->> unknown
SQL state: 42883
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Character: 2822
任何人都可以提出一個解決這個問題,或者另一種方式來做到這一點?
感謝
修復它,非常感謝。是內部加入最好的方式來做到這一點? – janderson
我仍然需要將它輸入到上面的輸出中,我怎樣才能加入到我以前的查詢中? – janderson