I have a bunch of product data in my DB. Each product has a certain ShopID which tells me to which shop it belongs.
I want all products with ShopID 1,4,7 appear last in the results.
How can I do that?
Sample Code
SELECT * FROM Tablename WHERE Name LIKE %red% ORDER BY ShopID ASC
Best Regards,
D.
if ShopID is not saved as comma separated value, you can use MySQL's FIELD()
ORDER BY FIELD(ShopID, 1,4,7) ASC, ShopID ASC
SQLFiddle Demo
the reason why 1,4,7 appears on the last part of the result list is because FIELD() returns the index that was specified on the list. in this case, any number that is not in 1,4,7 has an index 0 making it first on the list.
MySQL Documentation: FIELD()
Another alternative option would be to use a CASE statement in your ORDER BY clause:
SELECT *
FROM Tablename
WHERE Name LIKE '%red%'
ORDER BY CASE WHEN ShopID IN (1,4,7) THEN 1 ELSE 0 END, ShopID
SQL Fiddle Demo
Use this:
ORDER BY (ShopID IN (1, 4, 7)), ShopID
The ShopID IN expression will return 0 for rows that don't match, 1 for the rows that do.
Related
I have a table with a column called "myorder". I want to only order the first 5 elements in ascending order by using the column "myorder" and then the rest of the elements ordererd by id in descending order. I've tried but I don't seem to get this 100%. I have created a sqlfiddle with this simple example. Can anybody help me?
The order in the sqlfiddle should be: Blue, Brown, Yellow, Red, Green, Orange, Gray, Black, White.
maybe try
SELECT * from tbl ORDER BY IF(myorder=0, 2147483647, myorder) ASC, id DESC
if by "first 5" you mean ones with nonzero myorder
Append this to the end of your sql statement:
ORDER BY FIELD(id, 3,4,5,1,2,9,8,7,6)
This will manually sort the results based on the id field in the specified order getting the colours in order.
Alternatively you could:
ORDER BY FIELD(NAME, BLUE,BROWN,YELLOW......)
Union does not preserves order, at least not in all databases.
To get this done you need to select a fake column and use order on the results (total)
Here is a solution:
(
SELECT Id, myorder, myorder as fake, name from tbl WHERE myorder!=0) UNION
(SELECT id, myorder, 2000 as fake,name from tbl WHERE myorder=0) ORDER BY fake asc, id desc
This Will work in any case, as long as you keep the fake number high enough.
Can we have NULL value instead of zero when myorder is not specified?
If so we can do this:
SELECT * from tbl ORDER BY -myorder DESC, id DESC
Fiddle:
http://sqlfiddle.com/#!2/ef9ee/4
Hint on forcing nulls to sort last: MySQL Orderby a number, Nulls last
Use a CASE statement and the following trick (for example):
SELECT *,
CASE myorder
WHEN 0 THEN id
ELSE 99999999 - myorder
END AS ord
FROM tbl
ORDER BY ord DESC
SQL Fiddle
I have a table with a column containing productnames.
I want to sort it by productname ascending, BUT i want the productnames containing the word "accessory" to be sorted LAST.
How can this be done?
This is a common way to do this:
SELECT * FROM my_table
ORDER BY product_name LIKE '%accessory%', product_name
or
SELECT * FROM my_table
ORDER BY LOCATE('accessory', product_name), product_name
The clause product_name LIKE '%accessory%' is a Boolean expression, which returns 0 or 1, so all the rows that don't match will return 0 and will appear earlier in the sort order.
LOCATE('accessory', product_name) works similarly, but will return 0 for no match or the integer location of the first match. In this case, there's little difference between the two.
SELECT *,
(CASE WHEN `productname` LIKE '%accessory%' THEN 1 ELSE 0 END) AS `relevance`
FROM `tablename` ORDER BY `relevance`, `productname` ASC
You can give relevance based on conditions in mysql using case.
Obviously you can add your WHERE clause in there just before the ORDER BY statement, but for this example I just select everything
I have a simple query, but I would like to see the results in a specific way. I would like to see 'N/A' at the top of the result, without having to result to "Case When Then"
Select *
From Ordertype
Results:
Car21
Car34
Bus42
N/A
Thanks,
There are no 'overrides' for ORDER BY, if you want the specific order you're asking for, you'll have to use the CASE:
SELECT type
FROM OrderType
ORDER BY
CASE
WHEN type = 'N/A' THEN 1
ELSE 2
END
,type
If you want an arbitrary order that is not tied directly to the structured of a column (alphabetical/numerical) but rather to it's importance which only you know in your head it can be useful to add a Rank column to your table.
Column1 Rank
Car21
Car34 2
Bus42 1
N/A 99
then you can do
select Column1
from Table
order by rank desc, column1
This will put highly ranked items first then low ranked items, then when rows don't have a rank it will sort them alphabetically by column1
You can try this:
SELECT * FROM ordertype ORDER BY ID DESC
to see the newest ones 1st
I know that I can surface a row in a query by using it in the ORDER BY like this :
SELECT IF(`category` IS NOT NULL,`category`,"Uncategorized") AS `category` FROM `table` ORDER BY `category`="Uncategorized" DESC
Which will make the first row always contain "Uncategorized", however I have multiple rows that contain it that I also want surfaced. Here are two sample sets of returned data:
What I'm getting:
Uncategorized
Science
Health
Uncategorized
Wellness
What I want:
Uncategorized
Uncategorized
Health
Science
Wellness
I have tried a number of other things including a CASE and also using a conditional IF. What am I doing wrong?
The reason why it is not working is because the ORDER BY clause is comparing with the column name category and not on the alias given on the column.
SELECT IF(category IS NOT NULL,category,'Uncategorized') category
FROM `table`
ORDER BY IF(category IS NOT NULL,category,'Uncategorized')='Uncategorized' DESC
you can alternatively use COALESCE or IFNULL to make it shorter
SELECT COALESCE(category, 'Uncategorized') category
FROM `table`
ORDER BY COALESCE(category, 'Uncategorized') = 'Uncategorized' DESC, category
You need to use the function in the ORDER BY clause.
SELECT IF(`category` IS NOT NULL,`category`,"Uncategorized") AS `category`
FROM `table`
ORDER BY IF(`category` IS NOT NULL,`category`,"Uncategorized")="Uncategorized" DESC
You can create a custom ordering via FIELD()
...
ORDER BY FIEID(category,
'Uncategorized',
'Health',
'Science'
'Wellness')
The FIELD() function returns the index of the 1st parameter in the others.
I have a MySQL database and a have a funny question.
I need to order the results of a query by a field which has entries of 1,2,3 or 4, ordered descending but with 4 at the end.
So I wish to have the results in the following order
3's
2's
1's
4's
Is this possible at all?
I know I can do order the result array in php but unfortunately I need to do this in an sql statement.
If the field is an int,
ORDER BY (fieldname = 4) DESC, fieldname DESC
should do the trick.
Here is another cool way
ORDER BY MOD(fieldname,4) DESC,fieldname
If the result is a CHAR(1) then
ORDER BY LOCATE(fieldname,'3214'),fieldname
add this to the order
ORDER BY
CASE field_name WHEN 4 THEN 1
ELSE 2
END
this will return the result of the query order using the value of the field