本文介绍了将事物的顺序存储在MySQL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个如下表:

name VARCHAR(50) PRIMARY KEY NOT NULL
ordernum TINYINT UNSIGNED NOT NULL

也可以说我有3行.

something     - 1
somethingelse - 2
somethingmore - 3

如果我想插入另一个名为something1的条目,并将其ordernum设置为2,如何对ordernum为2或更大的所有行进行重新排序?即somethingelse变为具有3的序号,而somethingmore变为具有4的序号?

If i want to insert another entry called something1, and give it an ordernum of 2, how do I reorder all the rows that has an ordernum of 2 or greater? i.e. somethingelse becomes has an ordernum of 3, and somethingmore has an ordernum of 4?

我听说您可以通过FIELD()来做到这一点,但是我不确定该怎么做.

I've heard the you can do it via FIELD(), but I'm unsure how to exactly.

如果不可能,可以用PHP吗?

If it's not possible, anywy to do it in PHP?

推荐答案

在您的示例中:

UPDATE `table` SET `ordernum` = `ordernum` + 1 WHERE `ordernum` >= 2
INSERT INTO `table` (`name`, `ordernum`) VALUES ('something1', 2)

这篇关于将事物的顺序存储在MySQL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 07:58