简体   繁体   English

MySQL按值排序列

[英]MySQL sort column by values

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. 我想要实现的是我获得所有产品,按brand_id排序。 First all with brand_id 4, then 1 then 6 and then the rest. 首先使用brand_id 4,然后是1然后是6,然后是其余部分。

Here is my example on jsfiddle . 这是我在jsfiddle的例子。

If not working (jsfiddle not working fine here), see my code below: 如果没有工作(这里jsfiddle工作不正常),请参阅下面的代码:

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);

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. 如果brand_id中没有brand_id则返回0,因此不存在的品牌将位于顶部。 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. 所有值的顺序相反,然后您必须按DESC顺序排序。

Normally, when you use field() for sorting you also have in : 通常情况下,当您使用field()进行排序,你还可以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. 这个时间更长,但目的很明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM