Sort Mysql results by preference

Asked

Viewed 75 times

2

I own a table of produtos where there is the primary column id, wish to select products with the probable name of "%TV%" however i want it to be ordered so DESC normally, however I want some IDS come before others, the IDS that are in the promotion, for example 5, 4 respectively.

In this example the result order (by ID) should be: 5, 4, e depois os outros, como 1, 2, 3, 6...

id | name     |
---------------
 1 | tv       |   
 2 | core     |   
 3 | tv other |   
 4 | tv board |   
 5 | apple TV |   
 6 | core     |   
  • And how do you know which ones IDS products on sale? There is another table related?

  • @Marcelodeandrade not, those IDS would be directly inserted in the same query..

  • No no, but just by this table with only these two fields has no way of knowing which IDS are on sale. How do you define this?

  • @Marcelodeandrade they are defined manually, why they are fixed, it is as if I reserved 5 promotions, in case 5 IDS (1-5) and I put that product with one of these IDS.

  • But there’s some kind of column flag true/false that indicates that that product is on sale? If not, you need to review how is the relational structure of that.

  • @Marcelodeandrade was thinking of making two ORDER? I thought of something related but unfortunately the structure does not allow. There is no indicator other than the IDS special.

  • Is there a way to add at least one column to indicate that the product is on sale? Special IDS are fixed?

  • @Marcelodeandrade yes, they are fixed (I mean fixed but are changed in a long term). Unfortunately no, this indicator that is on sale or is not just the IDS that I receive.

Show 3 more comments

1 answer

4


I think that solves your problem:

SELECT *
FROM produtos
ORDER BY (id IN (5,4)) DESC, id

Browser other questions tagged

You are not signed in. Login or sign up in order to post.