算法用于管理SQL表中的位置算法、位置、SQL

2023-09-11 02:19:54 作者:等不回的记忆'

我有一个小小的疑问,如何管理下面的情况。 在一个数据库表我保存不同列中的相关数据,并在年底我保存在一个名为列位置的确切顺序。 这个表被绑定到一个网格。现在我实现,这将使改变位置到行的功能,但我仍然需要更新数据库。我问什么是最好的做法还是最方便的方式来实现这一目标?

I have a small doubt, how to manage the following situation. In a DB table i save the relevant data in different columns and at the end i save the exact order in a column called position. This table is binded to a grid. Now I'm implementing the functionality that will make change the position to the rows, but I need still to update the DB. I was asking what is the best practice or the most convenient way to achieve this?

和建议是值得欢迎的。

示例

名称位置

ABC 1 的

DEF 2 的

GHJ 3 的

现在我按一下按钮,我得到以下

Now I click on the button and I get the following

名称位置

DEF 1 的

ABC 2 的

GHJ 3 的

我希望我已经解释了自己!

I hope that I have explained myself!

3列ID1,ID2,位置 TABLE1   ID1和ID2是FK及本表有基于ID1和ID2 一个PK   当我选择要显示的数据我用下面的查询   SELECT名称等从​​Table 2 INNER JOIN上的表1 ID1 = ID1 WHERE ID2 = 511   ORDER BY位置

TABLE1 with 3 columns ID1, ID2, POSITION ID1 AND ID2 are FK's and the table has a PK based on ID1 and ID2 When I select the data to display I use the following query SELECT NAME, ETC FROM TABLE2 INNER JOIN TABLE1 ON ID1 = ID1 WHERE ID2 = 511 ORDER BY POSITION

现在我需要改变位置上的两个元素,因此在TABLE1行   例如311,511,5需要成为311,511,4,那就是433,511,4需要的行   成为433,511,5。与此相反的。

Now I need to change the position on two elements so the row in TABLE1 for example 311,511,5 needs to became 311,511,4 and the row that was 433,511,4 needs to became 433,511,5. The opposite.

我希望这有助于清除出我的问题。

I hope that this helped to clear out my question.

干杯!

推荐答案

当你说:改变位置到行的,你的意思动行上下贯通表(相对以位置序)?

When you say: "change the position to the rows", do you mean moving rows up and down through the table (relative to position ordering)?

如果是这样,移动的行了,需要更换位置以previous行。要移动它,你需要与下一行做同样的。根据特定的SQL方言的语法不同行交换值可能会类似于此:

If so, to move the row up, you need to exchange the position with previous row. To move it down, you need to do the same with the next row. Depending on your particular SQL dialect, the syntax for exchanging values from different rows will probably look similar to this:

UPDATE YOUR_TABLE
SET position =
    CASE position
    WHEN 2 THEN 3
    WHEN 3 THEN 2
    END
WHERE position IN (2, 3)

该示例将第3行和第二行了。根据您的需要替换2和3 ...

This example moves the row 3 up and row 2 down. Replace 2 and 3 according to your needs...

顺便说一句,这应该工作,即使没有对位置UNIQUE约束(甲骨文下确认)。

BTW, this should work even if there is a UNIQUE constraint on position (confirmed under Oracle).

有关更多的想法,你可以看看这个问题。

For more ideas, you may take a look at this question.