J
J
Jazper2015-06-13 08:12:45
PostgreSQL
Jazper, 2015-06-13 08:12:45

How to make a request in postgres?

There are 2 tables

users:
 id SERIAL PRIMARY KEY,
 username VARCHAR(40) NOT NULL,
 rating INTEGER

and
games:
 id SERIAL PRIMARY KEY,
 player1id INTEGER NOT NULL,
 player2id INTEGER NOT NULL,
 score1 INTEGER NOT NULL,
 score2 INTEGER NOT NULL

How to properly link tables? How to make a query returning something like this structure -
[{ gameid,
 score1,
 score2,
 player1: [{ id, username, rating }],
 player2: [{ id, username, rating }]
}]

Many thanks in advance for your help!
UPD : problem solving query (thanks @chlp) -
SELECT games.*, row_to_json(player1) AS player1, row_to_json(player2) AS player2 FROM games
INNER JOIN users player1 ON (games.player1id = player1.id)
INNER JOIN users player2 ON (games.player2id = player2.id)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Rytikov, 2015-06-13
@Jazper

More or less like this

SELECT games.id AS gameid, player1.id AS player1_id, player2.id AS player2_id, games.score1, games.score2
FROM games
INNER JOIN users player1 ON (games.player1id = users.id)
INNER JOIN users player2 ON (games.player2id = users.id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question