Mysql sorted by field (with swirl)

I have a product table with a product name, two product attribute fields and a price field.

The problem is that I cannot change the way the database is structured. Each attribute field is equivalent and can be used.

primarily:

 NAME      | ATTRIBUTE_1 | ATTRIBUTE_2 | PRICE
 Tshirt    | red         | small       | 25
 Tshirt    | medium      | red         | 20
 Tshirt    | blue        | medium      | 30
 Tshirt    | blue        | large       | 16

Not the best mood, but how is it ...

I want to make a request that will do the following:

Show all blue t-shirts and order them at a price Show all other t-shirts ordered at a price after

I was thinking of something like field order, but since the color can be either in attribute 1 or in 2, these fields should be equivalent.

Any suggestions?

+3
source share
2 answers
SELECT NAME, ATTRIBUTE_1, ATTRIBUTE_2, PRICE
FROM products
ORDER BY (ATTRIBUTE_1 = 'blue' OR ATTRIBUTE_2 = 'blue') DESC, PRICE

(ATTRIBUTE_1 = 'blue' OR ATTRIBUTE_2 = 'blue') 1, true, 0, false, blue.

+3
select name, attribute_1, attribute_2, price
from Product
order by 
    case 
        when ATTRIBUTE_1 = 'blue' or ATTRIBUTE_2 = 'blue' then 0 
        else 1 
    end, 
    price
+2

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


All Articles