Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sql query that depends on field in row?

Tags:

sql

php

mysql

pdo

yii2

I have mysql table Vegetables with fields price and unit. Unit can be 1 or 2, it means kilogram (1) or ton (2). It is unit weight. Price depends on unit, so price=200 with unit=1 is less then price=20 with unit=2, because 1 ton = 1000 kilogram

Q: I have query like ... ORDER BY 'price' ACS. How to make order by price that depends on unit field of the same table? Just no idea how to do that..

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

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

like image 385
sirjay Avatar asked Oct 20 '15 20:10

sirjay


People also ask

How do you reference a field in SQL?

You use column-ref to reference a column (database field), optionally qualified by a table and/or schema name. The column reference comprises the data type of the database field that the column represents (see Data Types).

How do I specific rows in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

WHERE clause is used for rows or columns?

The WHERE clause is used in the selection of rows according to given conditions whereas the HAVING clause is used in column operations and is applied to aggregated rows or groups.


1 Answers

SELECT *
FROM Vegetables
ORDER BY IF(unit=1,price,price*1000) ACS
like image 89
Alex Avatar answered Oct 01 '22 06:10

Alex