Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort SQL records based on matched conditions

Tags:

sql

mysql

I have this query:

SELECT * FROM table WHERE key LIKE '1,2,3,%' OR key LIKE '1,2,%' OR key LIKE '1,%'

Is it posible to sort records returned from this query based on which conditions was matched first. I'd like to get all records that match key LIKE '1,2,3,%' first, then key LIKE '1,2,%' and the others after.

For example, if I have these records:

key: "1,2,3,4"
key: "1,2,5"
key: "1,4"
key: "1,2,5,6"
key: "1,3"
key: "1,2,3,4,7"
key: "1,2,4"

I would like them to be sorted like so:

key: "1,2,3,4"
key: "1,2,3,4,7"
key: "1,2,4"
key: "1,2,5"
key: "1,2,5,6"
key: "1,3"
key: "1,4"

Is it possible to do?

like image 895
remi Avatar asked May 09 '26 03:05

remi


2 Answers

Use MATCH ... AGAINST and order by rank. It exactly does what you want.

like image 152
shamittomar Avatar answered May 10 '26 15:05

shamittomar


.... ORDER BY CASE
WHEN key LIKE '1,2,3,%' THEN 1
WHEN key LIKE '1,2,%' THEN 2
ELSE 3
END

like image 26
a1ex07 Avatar answered May 10 '26 17:05

a1ex07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!