简体   繁体   中英

MYSQL query: Sort by input user based on numbers

I have records in a mysql table. Users can give their 4-number postal code, the mysql query need to order the results based on the inputted postal code.

For instance three records with the row 'postalcode' > 5000, 5001, 5002 If a user gives 5010 as input the mysql query output needs to be so that the row with 5002 will display first.

Can someone help me out? I tried the search function, but I think i am not using the right english terms to what i mean.

Not sure how exactly your data set is setup.. but you can do a conditional order

ORDER BY
    CASE WHEN postalcode < your_code THEN 1
         WHEN postalcode = your_code THEN 2
         WHEN postalcode > your_code THEN 3
         ELSE 4
    END

the logic will most likely need to be changed around but that is the general idea.. where 1 is before 2 which is befor 3.. you can change it to mold however you need it to be.. but without data and the table schema i'm limited to just this

DEMO

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