Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以指定MySQL索引的排序顺序?_Mysql_Mysql 5.7 - Fatal编程技术网

是否可以指定MySQL索引的排序顺序?

是否可以指定MySQL索引的排序顺序?,mysql,mysql-5.7,Mysql,Mysql 5.7,我有一个items表,其中包含category\u id字段。 按照类别\u id对项目进行排序有一个特定规则。 我通常对数据进行如下排序: SELECT * FROM items ORDER BY FIELD(category_id, 2, 5, 1, 4, 3) -- In this example, the "rule" is sorting in order of (2, 5, 1, 4, 3) ALTER TABLE items ADD ( category_

我有一个
items
表,其中包含
category\u id
字段。 按照
类别\u id
对项目进行排序有一个特定规则。 我通常对数据进行如下排序:

SELECT * FROM items ORDER BY FIELD(category_id, 2, 5, 1, 4, 3)
-- In this example, the "rule" is sorting in order of (2, 5, 1, 4, 3)
ALTER TABLE items ADD (
  category_ord int GENERATED ALWAYS AS (FIELD(category_id, 2, 5, 1, 4, 3)) VIRTUAL 
);
CREATE INDEX idx_items_category_ord ON items(category_ord);

SELECT * FROM items ORDER BY category_ord;
在这种情况下,简单地在
category\u id
字段上创建索引并不能加快对项目的排序,因为索引对category\u id的排序就像(1、2、3、4、5)一样递增

在类别id字段上创建索引时,是否可以指定排序规则? (然后简单地
SELECT*FROM items ORDER BY category_id
works)


或者我必须创建另一个字段,如
sorted\u category\u id
,它根据顺序规则进行排序吗?

如Akina所说,我可以使用生成的列。

将列添加到
items
表中并在其上添加索引确实是一个注重速度的解决方案。通过将其设置为生成列,可以确保一致性;通过将其设置为虚拟列,可以将额外数据移动到索引中(如果创建了索引)。因此,请像这样进行:

SELECT * FROM items ORDER BY FIELD(category_id, 2, 5, 1, 4, 3)
-- In this example, the "rule" is sorting in order of (2, 5, 1, 4, 3)
ALTER TABLE items ADD (
  category_ord int GENERATED ALWAYS AS (FIELD(category_id, 2, 5, 1, 4, 3)) VIRTUAL 
);
CREATE INDEX idx_items_category_ord ON items(category_ord);

SELECT * FROM items ORDER BY category_ord;
可供替代的 或者,标准化的方法是向
类别
表中添加一列。如果您有许多类别,这将对性能产生轻微影响,但不会造成一致性问题,并节省空间。要实现该想法,请按以下步骤进行:

如果您没有该
类别
表,请创建它:

CREATE TABLE category(
  id int NOT NULL PRIMARY KEY,
  ord int NOT NULL,
  name varchar(100)
);
根据需要填充
ord
字段(或任何您想要调用的字段):

INSERT INTO category(id, ord, name) VALUES
(1, 30, 'cat1'),
(2, 10, 'cat2'),
(3, 50, 'cat3'),
(4, 40, 'cat4'),
(5, 20, 'cat5');
并在
ord
列中添加索引:

CREATE INDEX category_ord ON category(ord);
现在的问题是:

SELECT * 
FROM items 
INNER JOIN category 
ON items.category_id = category.id
ORDER BY category.ord;
数据库引擎现在可以决定是否使用
ord
列上的索引,这取决于它自己的分析。如果要强制使用它,可以使用
强制索引

SELECT * 
FROM items 
INNER JOIN category FORCE INDEX category(category_ord) 
ON items.category_id = category.id
ORDER BY category.ord;

请注意,引擎还可以使用
项.category\u id
上的索引进行逐值查找。

使用生成的列及其索引。使用本栏进行订购。谢谢!当我有一个单独的分类表时,另一种方法也很好。