Search code examples
mysqlselectlimitmultiple-columns

Selecting serial and IP, but the rows with the same IP first


I have a table AKA (Also Known As) to store players names which connects to the server. I have few columns in it: ID, Date, IP, Serial, Country and Name.

I want to select from it just 20 rows, but I need the rows which have the same IP as the specified one (player's IP) to be the first (for example: the first 5 rows would have the same IP and different Serial, and the next will have another IP), so if there are 20 rows there will be shown first the rows with the same IP.

This is what I made:

SELECT * FROM `AKA` WHERE ( `IP` = '%s' OR `Serial` = '%s' ) AND `Country` = '%s' ORDER BY `Date` DESC LIMIT 20

but I don't know how to sort it by Date and same IP first, then by Date.

I hope that you understand by question, thanks !


Solution

  • SELECT * FROM `AKA` 
    WHERE ( `IP` = '%s' OR `Serial` = '%s' ) AND `Country` = '%s' 
    ORDER BY `IP` <> '%s' ASC,
             `Serial` <> '%s' ASC,
             `Country` <> '%s' ASC,
             `Date` DESC 
    LIMIT 20