MySQL Selecting wrong column value in Group By query - mysql

Here's a real noobish MySQL query problem I'm having.
I have a high score table in a game I'm writing. The high score DB records a name, level, and score achieved. There are many near duplicates in the db. For example:
Name | Level | Score | Timestamp (key)
Bob 2 41 | 1234567.890
Bob 3 15 | 1234568.890
Bob 3 20 | 1234569.890
Joe 2 40 | 1234561.890
Bob 3 21 | 1234562.890
Bob 3 21 | 1234563.890
I want to return a "highest level achieved" high score list, with an output similar to:
Name | Level | Score
Bob 3 21
Joe 2 40
The SQL Query I currently use is:
SELECT *, MAX(level) as level
FROM highscores
GROUP BY name
ORDER BY level DESC, score DESC
LIMIT 5
However this doesn't quite work. The "Score" field output always seems to be randomly pulled from the group, instead of taking the corresponding score for the highest level achieved. Eg:
Name | Level | Score
Bob 3 41
Joe 2 40
Bob never got 41 points on level 3! How can I fix this?

You'll need to use a subquery to pull the score out.
select distinct
name,
max(level) as level,
(select max(score) from highscores h2
where h2.name = h1.name and h2.level = h1.level) as score
from highscores h1
group by name
order by level desc, score desc
Cheers,
Eric
It irks me that I didn't take the time to explain why this is the case when I posted the answer, so here goes:
When you pull back everything (*), and then the max level, what you'll get is each record sequentially, plus a column with the max level on it. Note that you're not grouping by score (which would have given you Bob 2 41, and Bob 3 21--two records for our friend Bob).
So, how the heck do we fix this? You need to do a subquery to additionally filter your results, which is what that (select max(score)...) is. Now, for each row that reads Bob, you will get his max level (3), and his max score at that level (21). But, this still gives us however many rows Bob has (e.g.-if he has 5 rows, you'll get 5 rows of Bob 3 21). To limit this to only the top score, we need to use a DISTINCT clause in the select statement to only return unique rows.
UPDATE: Correct SQL (can't comment on le dorfier's post):
SELECT h1.Name, h1.Level, MAX(h1.Score)
FROM highscores h1
LEFT OUTER JOIN highscores h2 ON h1.name = h2.name AND h1.level < h2.level
LEFT OUTER JOIN highscores h3 ON h1.name = h3.name AND h2.level = h3.level AND h1.score < h3.score
WHERE h2.Name IS NULL AND h3.Name IS NULL
GROUP BY h1.Name, h1.Level

This is efficient.
SELECT h1.Name, h1.Level, h1.Score
FROM highscores h1
LEFT JOIN highscores h2 ON h1.name = h2.name AND h1.level < h2.level
LEFT JOIN highscores h3 ON h1.name = h3.name AND h1.level = h3.level AND h1.score < h3.score
WHERE h2.id IS NULL AND h3.id IS NULL
You're looking for the level/score for which there is no higher level for that user, and no higher score that that level.

Interesting problem. Here's another solution:
SELECT hs.name, hs.level, MAX(score) AS score
FROM highscores hs
INNER JOIN (
SELECT name, MAX(level) AS level FROM highscores GROUP BY name
) hl ON hl.name = hs.name AND hl.level = hs.level
GROUP BY hs.name, hs.level;
Personally, I find this the easiest to understand, and my hunch is that it will be relatively efficient for the database to execute.
I like the above query best, but just for kicks... I find the following one amusing in a kludgey sort of way. Assuming score can't exceed 99999...
SELECT name, level, score
FROM highscores hs
INNER JOIN (
SELECT name, MAX(level * 100000 + score) AS hfactor
FROM highscores GROUP BY name
) hf ON hf.hfactor = hs.level * 100000 + hs.score AND hf.name = hs.name;

Related

multiple LEFT JOIN using LIMIT on one of the joins

I looked around for answers to this question but all the ones I tried simply didn't work. The other answer suggestions all threw errors for me. Maybe it's because I'm using using MariaDB ?.
SELECT * FROM 'view_winners'
I need top 3 in column 'class'
table view_winners is multiple left joins and I could not figure out how to limit 3 of the left join on table allClasses.
view_winners is:
`$view = "view_winners";
$db->query("DROP $view");
$db->query("CREATE VIEW $view AS
SELECT *
FROM thw22 evnt
LEFT JOIN allUsers usr
ON usr.user_id = evnt.e_owner_id
LEFT JOIN hw_vehicles veh
ON veh.vehicle_id = evnt.e_vehicle_id
LEFT JOIN hw_m_vehicle_class mcls
ON mcls.v_class_id = evnt.e_class_id
LEFT JOIN allClasses cls
ON mcls.cvm_id = cls.class_id
LEFT JOIN hw_v_scores sco
ON sco.v_score_id = evnt.e_score_id
WHERE (cls.class_name <> '' OR cls.class_name IS NOT NULL)
AND (sco.total <> '' OR sco.total IS NOT NULL)
ORDER BY cls.vehicle_type ASC, cls.class_name ASC, sco.total DESC
");`
It's probably best if I could LIMIT 3 on LEFT JOIN allClasses but I can't figure that out. So I figured I would loop through the result and unset rows over 3 in class in PHP. But again I could not figure out how to compare rows as looping through.
I need help with the LIMIT 3 on the JOIN or how to compare the results unsetting rows.
entry
class
score
786
sally
99
234
sally
90
456
bob
45
621
joe
90
964
joe
80
548
joe
66
346
joe
22
900
frank
89
700
frank
86
800
frank
72
123
frank
70
860
frank
50
333
frank
45
Desired results:
entry
class
score
786
sally
99
234
sally
90
456
bob
45
621
joe
90
964
joe
80
548
joe
66
900
frank
89
700
frank
86
800
frank
72
Might this answer help
And to clarify, it appears that for example, you want AT MOST, 3 entries per class (person name per sample data). If one class has only a single entry, get it. However, if someone else has 8 classes you want only the first 3 based on some pre-determined priority ordering, such as top 3 scores.
In your case, the OVER is partitioned by the "class", and the order by will be the score DESC (descending). So having the view give you this extra computed column (per class), you can then filter WHERE finalColumnNameYouAssign <= 3
I just answered similar question yesterday. See How to limit SQL query with JOIN
Here's my solution based on 2 linked tables, users and history for each user. There is also another solution there depending on your MySQL version.
SELECT *
FROM
`users` AS u
LEFT JOIN `history` AS h ON u.id = h.user_id
WHERE
FIND_IN_SET(h.id, (SELECT `list` FROM
(SELECT user_id, SUBSTRING_INDEX(GROUP_CONCAT(id SEPARATOR ','), ',', 3) AS `list` FROM
(SELECT h.user_id, h.id
FROM
`users` AS u
LEFT JOIN `history` AS h ON u.id = h.user_id
) AS `a`
GROUP BY user_id
) AS `b`
WHERE b.user_id = u.id
) )
Instead of having so many joins and confusing myself badly, I made a couple different views that I will need anyway for other statistics. Then by simply ordering by class ASC, score DESC I have a very simple master list of all classes in order then scores highest to lowest (along with all the other joined data). After that I can compare each row and limit 3 as follows:
SELECT * FROM
(SELECT *,
#rn := IF(#prev = class_name,
#rn + 1, 1)
AS rn,
#prev := class_name
FROM view_allScores
JOIN (SELECT #prev := NULL, #rn := 0)
AS vars
) AS T1
WHERE T1.rn <= 3
The confusing thing was that I was trying to add a LIMIT to a join and that kept confusing me.

MySQL - Return list of top 5 users, while including logged in user

I'm trying to return the users with the top 5 highest scores in a database and assign each user a rank, which I can then display in a high score table. I want the high-score table to contain a maximum of 5 rows, but I also want it to show the rank of the logged-in user amongst the other players. Let's say the logged-in user is 'jennie'.
SELECT *
FROM (
SELECT *, #i := #i+1 i,
(SELECT COUNT(DISTINCT highscore) FROM users s
WHERE s.highscore>=r.highscore) AS rank
FROM users r JOIN (SELECT #i:=0) vars
ORDER BY highscore DESC
) x
WHERE name = 'jennie'
OR i <= 5
ORDER BY rank ASC;
(Using MySQL 5.0.96). Here is a fiddle showing off the query. My issue is the query operates differently based on one condition:
1: If jennie is in the top 5 results, 5 rows will be returned, containing jennie amongst the other users.
2: If jennie is not in the top 5 results, 6 rows will be returned, where the last row contains jennie.
How can I use somehow truncate the list of top users in case 2, from 5 users down to 4 users, so when jennie appears on the end she makes up the 5th row? Thanks for your help.
You can achieve your desired result by doing some clever ordering. First we order by whether rank is <= 4, then by whether the user is 'jennie' and her rank is > 5, and then by rank. This way, if jennie is outside the top 5, she will show as 5th; if she is inside the top 5, she will show in the appropriate position (because of the final order by rank).
SELECT *
FROM (SELECT u1.userid, u1.name, COUNT(u2.userid) + 1 AS rank
FROM users u1
LEFT JOIN users u2 ON u2.highscore > u1.highscore
GROUP BY u1.userid) r
ORDER BY rank <= 4 DESC, name = 'jennie' AND rank > 5 DESC, rank
LIMIT 5;
Output (for your sample data)
userid name rank
4 harry 1
7 phil 2
2 james 3
1 sam 4
6 jennie 7
Demo on dbfiddle
Output (for when jennie's score is 40)
userid name rank
4 harry 1
7 phil 2
6 jennie 3
2 james 4
1 sam 5
Demo on dbfiddle
Note I prefer to do ranking via LEFT JOIN queries, as variables can be problematic...

Select sum of zero if no records in second table?

I did some research and learned about the COALESCE(sum(num), 0) function. The issue is the example I found only related to using one table.
I am calculating a sum from a second table, and if there are no records for an item in the second table, I still want it to show up in my query and have a sum of zero.
SELECT note.user, note.product, note.noteID, note.note, COALESCE(sum(noteTable.Score), 0) as points
FROM note, noteTable
WHERE note.user <> 3 AND note.noteID = noteTable.noteID
I am only recieving results if there is an entry in the second table noteTable. If there are scores added for a note, I still want them to show up in the result with a points value of zero.
Table Examples:
Note
user | product | noteID |note
3 1 1 Great
3 2 2 Awesome
4 1 3 Sweet
NoteTable
noteID | score
1 5
The query should show me this:
user | noteID | sum(points)
3 1 5
3 2 0
4 3 0
But I am only getting this:
user | noteID | sum(points)
3 1 5
http://sqlfiddle.com/#!9/aae812/2
SELECT
note.user,
note.product,
note.noteID, note.note,
COALESCE(sum(noteTable.Score),0) as points
FROM note
LEFT JOIN noteTable
ON note.noteID = noteTable.noteID
WHERE note.user <> 3
and I guess you should add:
GROUP BY note.noteid
if you expect to get SUM for every user. So you want to get more then 1 record back.
First, learn to use proper JOIN syntax and table aliases. The answer to your question is SUM() along with COALESCE():
SELECT n.user, n.product, n.noteID, n.note,
COALESCE(sum(nt.Score), 0) as points
FROM note n LEFT JOIN
noteTable nt
ON n.noteID = nt.noteID
WHERE n.user <> 3
GROUP BY n.user, n.product, n.noteID, n.note;
You also need a GROUP BY.

SQL Query to Count who has the highest number of match victories

I'm creating a simple database which will allow me to track snooker results, producing head to head results between players. Currently I have 3 tables: (Player, Fixture, Result)
PlayerID PlayerName
1 Michael Abraham
2 Ben Mullen
3 Mark Crozier
FixtureID Date TableNo Group
1 07/12/2015 19:00:00 12 0
2 08/12/2015 12:00:00 9 0
ResultID FixtureID PlayerID FramesWon
1 1 1 3
2 1 3 1
3 2 1 2
4 2 3 5
As you can see in the Result table, Player1 has played Player3 two times, with Player1 winning the first match 3-1, and Player3 winning the second match 5-2. I would like a query which returns the total number of matches won between the two players. In this case the expected output should be:
PlayerID MatchesWon
1 1
3 1
Any help would be appreciated - I'm not even sure if this can be achieved via a query
I agree using windowing function would be best way to go if available (SQL Server for example)
Might be possible with a straight SQL method this way (given that the one having most wins in a "fixture" is the match winner)
SELECT PlayerId, FixtureID, Count(*) As MatchesWon
FROM Result r
WHERE r.Frameswon = (SELECT MAX(frameswon) FROM Result r2
WHERE
r.FixtureId = r2.FixtureId)
GROUP BY PlayerID,FixtureId
OR if can leave out the fixtureId, and filter for just the 2 players something like this one as well. with data given above should bring the sample results.
SELECT PlayerId, MatchesWon
FROM
(
SELECT FixtureID,PlayerId, Count(*) As MatchesWon
FROM Result r
WHERE r.Frameswon = (SELECT max(frameswon) FROM Result r2
WHERE
r.FixtureId = r2.FixtureId)
GROUP BY FixtureId,PlayerID
) s
WHERE
PlayerID IN (1,3)
Perhaps this would work for you:
select playerid, count(*) as matcheswon
from result as r1
where frameswon =
(
select max(frameswon)
from result as r2
where r2.fixtureid = r1.fixtureid
)
group by playerid
In a fiddle here: http://sqlfiddle.com/#!9/60821/2
This is the alternative you can try.
SELECT r.PlayerID, COUNT(r.PlayerID)
FROM (
SELECT FixtureID, MAX(FramesWon) AS FramesWon
FROM `result`
GROUP BY FixtureID
) win
INNER JOIN result r ON win.FixtureID = r.FixtureID AND win.FramesWon = r.FramesWon
GROUP By r.PlayerID

Mysql Get Max Number of a group than make new group by that max number

I have a table, it similar with this table
ID Name Age Status
1 John 32 Life
2 Andre 99 Life
3 Anton 89 Dead
4 Maria 99 Life
5 Mario 13 Life
6 Santi 89 Dead
7 Anggy 56 Dead
8 Amir 99 Life
I want to do something like this
1. Group rows by status (Life)
2. Get the max Age from that group (99) (only the max number need)
4. Make new group by age and sort it by ID.
The result will be
8 Amir 99 Life
4 Maria 99 Life
2 Andre 99 Life
Any way to use only 1 line query for that job? with some (php) data procesing its not to hard to get the result i want, but i want to make code as clean as posible, so maybe i can do that 3 step in just a single query?
I think the right logic is:
select t.id, t.name, t.age, t.status
from table t join
(select max(t2.age) from table t2 where t2.status = 'life') m
on t.age = m.age
where t.status = 'life'
order by id desc;
select id, name, age, status
from thetable
where age =
(select max(age)
from thetable
where status="Life"
)
where status="Life"
order by id desc
Use the below mentioned query :
SELECT
*
FROM
t4
CROSS JOIN
(SELECT
MAX(`age`) AS 'age'
FROM
t4
WHERE
`status` = 'Life') AS t5
WHERE
`status` = 'Life' AND t4.`age` = t5.age
ORDER BY `id` DESC;
Check SQLFiddle