1

I'm trying to select the top 3 entries from a table called games that has foreign keys to the players and 2 ints for individual scores for the host and opponent.

The Query:

SELECT 
   games.id, games.host_score, games.opponent_score, player.name 
FROM games, player 
WHERE player.id = games.host_player_id 
      || player.id = games.opponent_player_id 
ORDER BY games.host_score, games.opponent_score DESC LIMIT 3

The query completes but it comes back out of order:

id  host_score  opponent_score  name
17  0           0               Temp2
17  0           0               Temp0
16  770         930             Temp0

When I run a query that doesn't have an OR it works. How can I get this method working?

Also is there a way to set a LIMIT of 50 but not count duplicates? For example if i wanted a limit of 2 but 3 people have the score 50 and 2 people have the score 20 it would return :

id  host_score  opponent_score  name
17  50          0               Temp2
17  50          0               Temp0
17  50          0               Temp1
17  20          0               Temp3
17  20          0               Temp4

Or would it be better to run it as seperate quesies in php?

4

3 に答える 3

0

1 つのゲームが 2 つの行 (1 つはホスト用、もう 1 つは対戦相手用) になるため、クエリが間違っていると思います。

ホスト名と対戦相手名の両方を取得したいので、playerテーブルに 2 回参加する必要があります。

SELECT g.id, g.host_score, g.opponent_score, hp.name as HostName, op.name as OpponentName
FROM games g join
     player hp
     on hp.id = g.host_player_id join
     player op
     on op.id = g.opponent_player_id 
ORDER BY g.host_score, g.opponent_score DESC
LIMIT 3
于 2013-01-16T19:08:48.993 に答える
0

高い順に並べたい場合は、フィールドごとに指定する必要があります

ORDER BY games.host_score DESC, games.opponent_score DESC 

順序を指定しないと、昇順が必要であると想定されるためです

于 2013-01-16T17:39:54.820 に答える
0

SQL では OR (|| の代わりに) を使用し、かっこを追加して読みやすくする必要があります。

WHERE (player.id = games.host_player_id) OR (player.id = games.opponent_player_id) 

スコア値で上位 50 のスコアを取得しますが、返される合計行数はそれより多くなる場合があります。以下のベアボーン クエリを使用して、必要に応じて微調整してください。

SELECT g1.id, g1.host_scores, COUNT(g2.host_scores) AS Rank
FROM games g1
WHERE Rank <= 50
JOIN games g2 ON (g1.host_scores < g2.host_scores) OR (g1.host_scores=g2.host_scores) 
GROUP BY g1.id, g1.host_scores
ORDER BY g1.host_scores DESC;

このような複雑さを避けるために、アプリケーションにデータを取得し、Java、PHP などのプログラミング言語でこれを簡単に行うことができることを付け加える必要があります。複数のクエリを作成することになるかもしれませんが、はるかに単純でより多くの時間の経過とともに維持可能。

于 2013-01-16T17:46:19.357 に答える