1

I want to sort my database result based on a column value. I thought I needed to do this:

SELECT * FROM products
ORDER BY FIELD(brand_id, 4, 1, 6)

But this doesn't sort my result at all. Or at least in a way I don't understand.

What I want to achieve is that I get all products, ordered by brand_id. First all with brand_id 4, then 1 then 6 and then the rest.

Here is my example on jsfiddle.

If not working (jsfiddle not working fine here), see my code below:

Schema:

CREATE TABLE `products` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `brand_id` int(10) unsigned NOT NULL,
  `price` decimal(8,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

INSERT INTO `products` (`id`, `brand_id`, `price`)
VALUES
    (1, 1, 10.32),
    (2, 4, 15.32),
    (3, 2, 23.32),
    (4, 6, 56.32),
    (5, 4, 23.32),
    (6, 4, 23.32),
    (7, 1, 25.32),
    (8, 5, 15.32),
    (9, 3, 55.32),
    (10, 5, 23.32);

2 Answers 2

2

The problem is here:

 FIELD(brand_id, 4, 1, 6)

will return 0 if brand_id is not present in the list, so brands not present will be at the top. You can use this:

ORDER BY FIELD(brand_id, 6, 1, 4) DESC

with all of the values in reverse order, and then you have to order in DESC order.

Sign up to request clarification or add additional context in comments.

1 Comment

This did the job! I forgot the DESC and I need to add the ID's in reverse order! Thanx! Was looking at it but just didn't understand what was going wrong!
1

Normally, when you use field() for sorting you also have in:

SELECT p.*
FROM products p
WHERE brand_id IN (4, 1, 6)
ORDER BY FIELD(brand_id, 4, 1, 6);

Then it works as advertised.

Instead of reversing values, you can also take a more explicit approach:

SELECT p.*
FROM products p
ORDER BY brand_id IN (4, 1, 6) DESC,
         FIELD(brand_id, 4, 1, 6);

This is longer, but the intention is clear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.