0

If i have a MYSQL table that sorts names and one table that sorts value.

Example this is how the table look like:

ID name   value
-- ------ -----
1  John     500
2  Rock     350
3  Wayne    700
4  John     350
5  Rock     250
6  Nick     100
7  Sweety    75
8  Lex      350

How do i display the total value for eache user? and also if i want to filter it to only show top 3 is there an easy command for that? Or do i need to make some kind of function.

In PHP

John 850
Wayne 700
Rock 600
Lex 350
Nick 100
Sweety 75
4

2 に答える 2

2

これは、集計によって実現できます。

SELECT ID, name, SUM(value) as total_score 
FROM user_scores 
GROUP BY name
ORDER BY total_score
于 2013-06-17T21:08:27.203 に答える
2

You need an aggregate function, specifically SUM. You can order a query by any value in the select list, and to go high-to-low just use the DESC keyword:

SELECT Name, SUM(value) AS TotalValue
FROM myTable
GROUP BY Name
ORDER BY TotalValue DESC

The AS TotalValue will ensure that the column name is TotalValue when you reference it in PHP.

于 2013-06-17T21:09:10.987 に答える