开发者

mysql order by field( with a twist)

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

The problem is that I can't change the way the database is structured. Each attribute fields are equivalent and either can be used.

basically :

 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 set up but that's how it is...

I want to do a query that will do the following :

Display all the blue tshirts first and order them by price Display all the other tshirts ordered by price after

I was thinking something like order by field, but sin开发者_如何学编程ce the color can be either in attribute 1 or 2 those fields need to be equivalents.

Any suggestions?


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') will be 1 if true, 0 if false, so sorting on that in descending order will sort the rows that have one attribute value of blue first.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜