简体   繁体   中英

How to write a SQL query for this logic (has_many, belongs_to association)?

The goal of this SQL query is to return the user with the most fight wins AND a count of the wins.

I have two tables: users and fights.

User has many fights Fight belongs to user

Fight has the following columns of concern:

  • challenger_id (user_id fk)
  • challengee_id (user_id fk)
  • challenger_won (boolean)

As you can see, a user can be a challenger or a challengee, but not both.

  • If the user is a challenger and the challenger_won = true, then it is considered a win.
  • If the user is a challengee and the challenger_won = false, then it is considered a win.
  • If the challenger_won = null, then just disregard it.

How would I write the SQL for this?

What about this?

SELECT a.fighter, COUNT(*) AS wins
  FROM (SELECT challenger_id AS fighter
          FROM fights
         WHERE challenger_won = TRUE
        UNION ALL
        SELECT challengee_id AS fighter
          FROM fights
         WHERE challenger_won = FALSE
       ) AS a
 GROUP BY a.fighter;

If challenger_won is NULL, both queries in the UNION will ignore the row, as required.

If you don't like UNION ALL, you can use, instead:

SELECT a.fighter, SUM(a.wins) AS wins
  FROM (SELECT challenger_id AS fighter, 'R' AS role, COUNT(*) AS wins
          FROM fights
         WHERE challenger_won = TRUE
         GROUP BY fighter, role
        UNION
        SELECT challengee_id AS fighter, 'E' AS role, COUNT(*) AS wins
          FROM fights
         WHERE challenger_won = FALSE
         GROUP BY fighter, role
       ) AS a
 GROUP BY a.fighter;

The first part of the UNION generates rows with 'R' as role (for 'challengeR won') and the fighter ID and a count of the fights won. The second part generates rows with 'E' as role (for 'challengeE won') and the fighter ID and a count of the fights won. The role is necessary in case some fighter won 3 fights as challenger and 3 fights as challengee; without the role, the two entries with the same fighter and count would be collapsed into one. You then sum the wins for each fighter in each role.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM