M
M
Maxim Timofeev2016-06-22 16:55:28
PHP
Maxim Timofeev, 2016-06-22 16:55:28

How to correctly compose an ORDER BY CASE query?

What am I doing wrong?
have a request

$query = Product::find()
->with(['image','salon'])
->joinWith('salonProduct', true, 'LEFT JOIN')
->orderBy([new \yii\db\Expression('
CASE salon_product.sort 
WHEN NULL 
THEN 50000 
ELSE salon_product.sort 
END
')]);

I expect that the sorting will go like this, first the fields where salon_product.sort is not null in ascending order, then those that are null
But I get it, it’s completely different. I can't even figure out why. But Starts with those where salon_product is missing.
I have a product and a salon_product table which has a product_id field. But not every product has a salon_product. Accordingly, I want to display first those for which there are in sort order, then the rest no matter how.
Here is the request:
SELECT `product`.* FROM `product` LEFT JOIN `salon_product` ON `product`.`id` = `salon_product`.`product_id` WHERE `cat_id`='1' ORDER BY CASE WHEN salon_product.sort = NULL THEN 50000 ELSE salon_product.sort END LIMIT 24

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
Urvin, 2016-06-22
@webinar

COALESCE(salon_product.sort, 50000)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question