temp-learn
temp-learn

Reputation: 537

sorting 2 Columns in mysql

i Have Following Mysql Query

SELECT DISTINCT
  main_Table.id,
  t1.percentage,
  t2.percentage
FROM image_new main_Table
  INNER JOIN (SELECT DISTINCT
    image_colors_new.image_id,
    image_colors_new.percentage
  FROM image_colors_new
  WHERE image_colors_new.s BETWEEN 80 AND 120 AND image_colors_new.h BETWEEN - 20 AND 20 AND image_colors_new.v BETWEEN 73 AND 103
  GROUP BY image_colors_new.percentage
  ORDER BY image_colors_new.percentage DESC) t1
    ON main_Table.id = t1.image_id
  INNER JOIN (SELECT DISTINCT
    image_colors_new.image_id,
    image_colors_new.percentage
  FROM image_colors_new
  WHERE image_colors_new.s BETWEEN - 20 AND 20 AND image_colors_new.h BETWEEN - 20 AND 20 AND image_colors_new.v BETWEEN 85 AND 115
  GROUP BY image_colors_new.percentage
  ORDER BY image_colors_new.percentage DESC) t2
    ON main_Table.id = t2.image_id

This Gives me Following Out Put

   id   percentage      percentage1
36888   32.975669099756 0.559610705596
54899   9.9722991689751 0.55401662049861
43584   9.9195710455764 9.3833780160858
61517   9.7938144329897 40.20618556701
78076   9.7267759562842 12.786885245902
52123   9.6916299559471 3.3039647577093
36378   9.5798319327731 18.655462184874
43820   9.5238095238095 10.31746031746
53579   9.4736842105263 5.6140350877193

but i want rows in following format i.e rows that have percentage with highest value must pop to top, from either of columns

id      percentage      percentage1
61517   9.7938144329897 40.20618556701
36888   32.975669099756 0.559610705596
36378   9.5798319327731 18.655462184874
78076   9.7267759562842 12.786885245902
43820   9.5238095238095 10.31746031746
43584   9.9195710455764 9.3833780160858
54899   9.9722991689751 0.55401662049861
52123   9.6916299559471 3.3039647577093
53579   9.4736842105263 5.6140350877193

Upvotes: 0

Views: 44

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

It sounds like you want to order by the larger of the percentage values. Add:

order by greatest(t1.percentage, t2.percentage) desc;

This should actually go in the outer query. Don't get in the habit of doing order by in subqueries. It might usually work, but there are no guarantees (and this is particularly true in other databases in multi-threaded implementations).

Upvotes: 4

Related Questions