しばらくの間私を悩ませてきたネスト/サブクエリについて質問があります。
私はPHPでゲームをプログラミングしています。私のシステムの非常に単純なバージョンでは、次の3つのテーブルがあります。
プレイヤー(各プレイヤーには1つのエントリしかありません):
| player_id | player_name |
統計(各プレイヤーは、ゲームごとに1つのエントリを持っています):
| stat_id | player_id | game_id | outcome |
ゲーム(各ゲームには1つのエントリがあります):
| game_id | game_name |
データベースにクエリを実行し、次のように構造化された行を持つテーブルを出力にします。
| player_name | count stats for player where outcome = 1 || count stats for player where outcome = 2 |
私は次のように機能しますが、よりスマートでより良い方法があると思います:
select a.player_name,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 1) as number_of_games1,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 2) as number_of_games2
from players a
また、外側の場所で「number_of_games1」または「number_of_games2」を使用できるようにしたいのですが、上記のアプローチではこれができません。
select a.player_name,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 1) as number_of_games1,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 2) as number_of_games2
from players a where number_of_games > 5
私がやりたいことをする最も賢い方法は何ですか?
ありがとう。
SUM()
条件付きの関数を使用して結合を使用できます。条件付きで使用するとSUM()
ブール値1または0になるため、b.outcome = 1
およびの目的の結果をカウントできます。b.outcome = 2
SELECT
a.player_id,
a.player_name,
SUM(b.outcome = 1) as number_of_games1,
SUM(b.outcome = 2) as number_of_games2
FROM players a
LEFT JOIN stats b ON(b.player_id = a.player_id)
GROUP BY a.player_id
HAVING number_of_games1 > 5
/* you can add second condition for number_of_games2
starting with any conditional operator
*/
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加