简体   繁体   中英

Join multiple tables and order by sum of row

Recently began working on a matchmaking system, where in this system there are 2 tables. One table is for matches and one table is for ranks.

The table for ranks starts off like this

table_ranks:

date
playeruid
rank

table_matches:

date
playeruid
playerpoints

I'm trying to now order the player by their points. However, in order to do this, I have made a query:

SELECT * FROM table_ranks ORDER by rank DESC

But now what I realize, is that I need to add the playerpoints on top of the rank. So basically, I need to add playerpoints to the player's current ranking. So, if I had this for an example row:

table_ranks:

2/20/15
Player1
56

table_matches:

2/27/15
Player1
5

I would need to build a query that takes the 56 of player1, looks for player1 in the matches and anywhere it sees it, it would need to add his 5 points making it a sum of 56. Once this is determined it would ORDER by this value in order to determine who is ranked with what. How do I begin my query? I understand that in order to join the tables, I need to start off like this:

"SELECT table_ranks. , table_matches. from table_ranks, table_matches ORDER by RANK..."

Then to finish it,I would have to take the current value of the rank, then grab the specific player it's referring to and take all the matches and add up all the playerpoints to his rank then to determine how to order it by.

Try this:

SELECT r.playeruid, r.date AS rank_date, m.date AS macthes_date, 
       (r.rank + m.playerpoints) AS total_points  
FROM table_ranks r INNER JOIN table_matches m ON r.playeruid = m.playeruid  
ORDER BY total_points DESC

This query assumes that playeruid is unique in both tables.

Try the following query. I tested on a similartable structure and it should work

 SELECT * , playeruid AS player_id, (
    SELECT SUM( playerpoints ) 
    FROM  `table_matches` 
    WHERE playeruid = player_id
 ) AS points
 FROM table_ranks 
 ORDER BY points DESC

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