Ordene la combinación que devuelve varias filas

In PostgreSQL 8.4 I have a join always returning 3 rows (they represent 3 players playing the game round librar) -

# SELECT r.rid, c2.pos, c2.money, c2.last_ip, c2.quit,
u.id, u.first_name
FROM pref_rounds r
JOIN pref_cards c1 USING (rid)
JOIN pref_cards c2 USING (rid)
JOIN pref_users u ON u.id = c2.id
WHERE c1.id = 'OK336197153288';
  rid   | pos | money |     last_ip     | quit |          id           | first_name
--------+-----+-------+-----------------+------+-----------------------+------------
 165684 |   0 |    14 | 77.91.175.242   | f    | OK336197153288        | Елена
 165684 |   1 |    -2 | 195.177.124.218 | f    | OK3982469933          | Константин
 165684 |   2 |   -14 | 92.243.183.44   | f    | MR438331292705069453  | Дмитрий

 165711 |   2 |    10 | 77.91.175.242   | f    | OK336197153288        | Елена
 165711 |   0 |    -2 | 195.177.124.218 | f    | OK3982469933          | Константин
 165711 |   1 |    -6 | 92.243.183.44   | f    | MR438331292705069453  | Дмитрий

 165764 |   1 |    13 | 77.91.175.242   | f    | OK336197153288        | Елена
 165764 |   2 |   -17 | 195.177.124.218 | f    | OK3982469933          | Константин
 165764 |   0 |     3 | 92.243.183.44   | f    | MR438331292705069453  | Дмитрий

Unfortunately they are not sorted by the pos (the 2nd column which is a position at a playing table).

Is there please a way in SQL to sort the above sets of 3 rows so that they always have the pos: 0 1 2 then again 0 1 2?

Or do I have to do it in my PHP script?

preguntado el 03 de mayo de 12 a las 07:05

(-1) I see no ORDER BY, solo un order-by tag ... what did you try/what's the "issue"? -

Of course I tried "order by", but missed that I can specify 2 columns there. -

2 Respuestas

Use the following sql query. It will give you the required result.

# SELECT r.rid, c2.pos, c2.money, c2.last_ip, c2.quit,
u.id, u.first_name
FROM pref_rounds r
JOIN pref_cards c1 USING (rid)
JOIN pref_cards c2 USING (rid)
JOIN pref_users u ON u.id = c2.id
WHERE c1.id = 'OK336197153288'
Order by r.rid asc, c2.pos asc
;

contestado el 03 de mayo de 12 a las 07:05

Quizás algo como esto:

SELECT r.rid, c2.pos, c2.money, c2.last_ip, c2.quit,
u.id, u.first_name
FROM pref_rounds r
JOIN pref_cards c1 USING (rid)
JOIN pref_cards c2 USING (rid)
JOIN pref_users u ON u.id = c2.id
WHERE c1.id = 'OK336197153288'
ORDER BY r.rid,c2.pos;

You first need to order by the r.rid entonces por c2.pos to get them order like you want

contestado el 03 de mayo de 12 a las 07:05

you can not write order by before where clause. - Sheikh Farooque

ORDER BY debería ser después WHERE. - damien_el_incrédulo

Lo siento por eso. Actualicé la respuesta - Arion

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.