命令连接返回多行

时间:2012-05-03 06:30:24

标签: sql postgresql sql-order-by join postgresql-8.4

在PostgreSQL 8.4中我有一个总是返回3行的连接(它们代表3个玩游戏的玩家摆脱) -

# 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  | Дмитрий

不幸的是,他们没有按 pos 排序(第二列是在比赛桌上的位置)。

在SQL中是否有一种方法可以对上面的3行进行排序,以便它们始终具有 pos :0 1 2然后再次为0 1 2?

或者我必须在PHP脚本中执行此操作吗?

2 个答案:

答案 0 :(得分:1)

使用以下sql查询。它会为您提供所需的结果。

# 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
;

答案 1 :(得分:1)

也许是这样的:

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;

您首先需要按r.rid订购,然后按c2.pos订购才能按照您的要求订购