Reputation: 130
I have a mysql table like this one (it's an example):
| ID | Product name | Price | TopProduct |
| 01 | Product 001 | 10.00 | 1 |
| 02 | Product 002 | 15.00 | 0 |
| 03 | Product 003 | 20.00 | 1 |
| 04 | Product 004 | 10.00 | 0 |
Where TopProduct is a flag that the user set on the admin system.
The products that have the flag (TopProduct) set to 1, should appear first on the list and then, after the query bring me all the flagged, it would then show the other products ordered by "ID"
So in the end result i would have a list like this:
The question is, how should i put together my query or queries? Any thoughts on that?
Upvotes: 0
Views: 585
Reputation: 43434
This can be solved this way:
select ProductName from table
order by TopProduct desc
HOWEVER, this will only work under the condition that TopProduct's max value is 1. I mean, if you can flag that column with a 2 in any row this won't work as that row will appear first. Is that the case?
In case it is, this is the query to sort all 1 at first regardless of the presence of any other number in the column:
select ProductName from table
order by if(TopProdct = 1, 1, 0) desc
Upvotes: 0
Reputation: 6190
You can do something like this
SELECT ID, ProductName, Price FROM product ORDER BY TopProduct, ID DESC
It will first order by TopProduct, Then again based on the ID
Upvotes: 0