Question:
I have a table with repeated Ids and with a JSON data that represents an alias “players_level”, I’m trying to group the Ids so I don’t have duplicated Ids but the problem is that when grouping the Ids I can’t get the row with the greater “players_level” alias, example I have this data:id | score | players | players_level |
---|---|---|---|
1 | 0 | {} | 0 |
16 | 1000 | {“1”: {“222”: [], “1232”: [], “2824”: [], “33332”: [], “66345”: []}} | 2 |
17 | 0 | {“1”: {}} | 1 |
16 | 500 | {“1”: {“2824”: [“148500”]}, “48”: {“2890”: []}} | 3 |
And I’m trying to group the data like this:
id | score | players | players_level |
---|---|---|---|
1 | 0 | {} | 0 |
17 | 0 | {“1”: {}} | 1 |
16 | 500 | {“1”: {“2824”: [“148500”]}, “48”: {“2890”: []}} | 3 |
As you can see the row 2 disappeared because its players_level was 2 and the fourth one has level 3… but when trying to group using multiple techniques with SQL (Group By, Order By, Max…) I can’t get the right row to output ๐
Can anybody help me please? I have a fiddle link with the data example:
https://www.db-fiddle.com/f/sfQVa722kfkNw2JyRdQJZr/0
Answer:
You can useHAVING
with a subselect with MAX
Schema (MySQL v5.7)
id | score | players | players_level |
---|---|---|---|
1 | 0 | {} | 0 |
17 | 0 | {“1”: {}} | 1 |
16 | 500 | {“1”: {“2824”: [“148500”]}, “48”: {“2890”: []}} | 3 |
View on DB Fiddle
If you have better answer, please add a comment about this, thank you!