1

I want to order ascending a MySQL query by this rule: x-y/x

x = price

y = price2

price and price2 are the columns from the MySQL table.

I have this query but unfortunately doesn`t work.

SELECT * 
FROM albums 
WHERE price2 > 1 
ORDER BY price - price2 / price ASC

Thanks for attention.

CBuzatu
  • 745
  • 5
  • 16
  • 29
  • 2
    What exactly do you mean by "doesn't work"? Is there an error? Do you get no results? Do you get results, but they aren't what you expect? Please add examples if you can. – Wiseguy Apr 23 '12 at 15:13
  • 1
    The query does give a result with no error at least, is the result somehow unexpected? http://sqlfiddle.com/#!2/05344/1 – Joachim Isaksson Apr 23 '12 at 15:16

3 Answers3

4

try this out:

$SQLquery = "SELECT * FROM albums WHERE price2 > 1 ORDER BY (price-price2)/price ASC";

or

$SQLquery = "SELECT * FROM albums WHERE price2 > 1 ORDER BY ((price-price2)/price) ASC";
orif
  • 362
  • 1
  • 4
  • 15
3

You should try:

SELECT * FROM albums 
WHERE price2 > 1 
ORDER BY ((price - price2) / price) ASC

or

SELECT albums.*, ((price - price2) / price) myvar FROM albums 
WHERE price2 > 1 
ORDER BY myvar ASC
Marco
  • 56,740
  • 14
  • 129
  • 152
  • This was the answer: `SELECT * FROM albums WHERE price2 > 1 ORDER BY (price - price2) / price ASC` – CBuzatu Apr 23 '12 at 15:18
0

Order By works based on specified column. You can create a view or temporary table from your base table containing a new column with the value based on that formula and then sort that column.

TS-
  • 4,311
  • 8
  • 40
  • 52