Charas
Charas

Reputation: 1837

CI Is there a way to query custom order_by

Is it possible to customize the order_by query in MySQL or in CI ? Such as I want my column to be ordered by ('1', '11', '4', '2', '21', '3', '5', '7') So if I query it as ASC the result will show in the order of my customized order.

If it is not possible, what is the best workaround to get these order ? Hoping for a simple solution just using the MySQL query.

All answers and suggestions are greatly welcomed. Thanks.

Upvotes: 1

Views: 368

Answers (2)

webpic
webpic

Reputation: 443

Try this one.

$this -> db -> order_by('FIELD ( table.id, 1, 11, 4,2,21,3,5,7 )');

link

Upvotes: 5

Jason Joslin
Jason Joslin

Reputation: 1144

Pure Mysql answer is yes you can order a field by a set list with the MYSQL FIELD() function

SELECT *
FROM mytable 
WHERE id IN ('1', '11', '4', '2', '21', '3', '5', '7')
ORDER BY FIELD(id, '1', '11', '4', '2', '21', '3', '5', '7')

Upvotes: 0

Related Questions