算法用于管理SQL表中的位置 [英] Algorithm for managing position in SQL table

查看:85
本文介绍了算法用于管理SQL表中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于算法用于管理SQL表中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆