Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql order by case when array

Tags:

php

mysql

I'd like to know if there is more efficient way to write the loop of cases.

$search = "ORDER BY CASE WHEN created_by = :created_by THEN -1                                             
           WHEN cat_id = 24  THEN -1 
           WHEN cat_id = 26  THEN -1 
           ELSE created_at END LIMIT :limit, :perpage";

I wonder if

WHEN cat_id = 24  THEN -1 
WHEN cat_id = 26  THEN -1 

could be

WHEN cat_id = IN(24,26) THEN -1

if not how can I go about it? Do I have to make some sort of a for loop?

like image 279
Katerpiler Avatar asked Aug 31 '26 14:08

Katerpiler


1 Answers

If it's just two values then you can use OR operator, e.g.:

WHEN (cat_id = 24 or cat_id = 26)  THEN -1

If you need to compare with multiple values but they are not sequencial then you can use IN operator, e.g.

WHEN (cat_id IN (24, 26))  THEN -1

If the values are in range then you can use BETWEEN, e.g.:

WHEN (cat_id BETWEEN 21 and 30)  THEN -1
like image 200
Darshan Mehta Avatar answered Sep 02 '26 04:09

Darshan Mehta



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!