Mysql
 sql >> база данни >  >> RDS >> Mysql

Динамично подреждане на сложна футболна лига в MySQL?

Нека го направим стъпка по стъпка:

Изберете спечелените игри у дома и резултата у дома:

   SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G WHERE 
      G.team_id = T.team_id #See 3. query and you'll understand
      G.home_score > away_score

Нека наречем този резултат HOME_GAMES.

Изберете спечелените игри и резултата от гостуванията:

SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
WHERE 
  G.team_id = T.team_id #See 3. query and you'll understand
  G.away_score > G.home_score

Нека наречем този резултат AWAY_GAMES.

Изберете общия брой спечелени игри и общия резултат:

   SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM
   (AWAY_GAMES) AS A, (HOME_GAMES) AS H, teams T 
   ORDER BY total_wins, total_score

==> Съберете всичко, като замените AWAY_GAMES и HOME_GAMES:

SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM 
  (SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
   WHERE 
     G.team_id = T.team_id #See 3. and you'll understand
     G.away_score > G.home_score) AS A, 

   (SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G 
   WHERE 
      G.team_id = T.team_id #See 3. and you'll understand
      G.home_score > away_score) AS H, 

   teams T
   ORDER BY total_wins, total_score 


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Mocha Test свързаност към DB

  2. Как да включите NULL стойности в заявка с Outer Join и Group By

  3. Съпоставяне, чувствително към главни букви в MySQL

  4. Как да се свържа с MySQL база данни от Clojure?

  5. Разбиране на застой в MySQL и PostgreSQL