How to execute sql query which depends on field in row?

I have a mysql Vegetables table with price and unit fields. The unit can be 1 or 2 , which means kilogram ( 1 ) or ton ( 2 ). This is a unit weight. The price depends on a unit, therefore price=200 with unit=1 less than price=20 with unit=2 , because 1 ton = 1000 kilograms

Q : I have a query like ... ORDER BY 'price' ACS . How to make order by price , which depends on the unit field of the same table? I just don’t know how to do it.

In words, it looks like ... ORDER BY {if(this.unit==1):price;else:price*1000} ACS

I am using yii2 for this project: Vegetable::find()->addOrderBy('price asc');

+5
source share
1 answer
 SELECT * FROM Vegetables ORDER BY IF(unit=1,price,price*1000) ACS 
+6
source

Source: https://habr.com/ru/post/1234154/


All Articles