【问题标题】:"Slot" depending on user id etc. sql“插槽”取决于用户 ID 等 sql
【发布时间】:2011-12-07 16:02:13
【问题描述】:

我有一张这样的桌子

id 项目用户槽

我希望 SLOT 依赖于用户 ID。

如果我有 4 列

id: 1
user: 1
item: 1
slot: 1

id: 2
user: 1
item: 1
slot: 2

id: 3
user: 1
item: 2
slot: 3

id: 4
user: 1
item: 2
slot: 4

如果我添加一个新项目,它应该自动被赋予插槽 5。但是如果我首先,比如说,删除(插槽 2 或将其移动到另一个插槽,新项目应该获得插槽号 2。这可能吗?用 SQL 吗?

Slot 基本上是放置“item”行的位置。

库存如下所示:

1 2 3 4 5
6 7 8 9 10
11 12 13 14
15 16 17 18
19 20

数字 1-20 是插槽。如果,假设上面的 4 个插槽被项目占用,则下一个项目应分配 5。但是如果我将一个项目(如插槽 2)移动到插槽 20,则下一个项目应放置在数字 2 上,因为它现在没有采取。如果 3-4 都被删除,然后添加一个项目,它将被放置在 3。

【问题讨论】:

  • 你能解释更多槽的概念吗?不是你的榜样,而是它代表什么以及你想要完成什么?
  • 所以您希望将新条目放入“下一个可用的最小数字槽”,对吗?

标签: sql gaps-and-islands


【解决方案1】:

您可以使用插入触发器来更新插槽,或者您可以在插入时自行确定第一个可用插槽。

至于确定第一个空闲槽号,你可以像其他人所说的那样使用循环检查,或者你可以有点创意:

SELECT min(rnumber)
from (SELECT slot, row_number() OVER (order by slot) as rnumber from <table_name> where slot is not null) as t
where slot <> rnumber

这将获得最小的空闲槽。如果所有插槽都被占用,则返回值为 null。您必须使用 max(slot)+1 获得下一个插槽。 您可以使用isnull(min(rnumber), (select max(slot)+1 from &lt;table_name&gt;) 代替 min(rnumber),因此最终查询如下所示:

SELECT isnull(min(rnumber), (select max(slot) + 1 from <table_name>))
from (SELECT slot, row_number() OVER (order by slot) as rnumber from <table_name> where slot is not null) as t
where slot <> rnumber

【讨论】:

  • 对本机函数'isnull'的调用中的参数计数不正确
  • @John 你用的是什么数据库?我正在使用 MSSQL msdn.microsoft.com/en-us/library/ms184325.aspx 如果您使用的是 MySQL,则可以使用 COALESCE 函数而不是 ISNULL
【解决方案2】:

选项 1

您需要在表上创建一个触发器以进行插入。

这是一个例子:

create trigger forinsertrig1 
on salesdetail 
for insert 
as 
if (select count(*) 
    from titles, inserted 
    where titles.title_id = inserted.title_id) !=
    @@rowcount 
/* Cancel the insert and print a message.*/
  begin
    rollback transaction 
    print "No, the title_id does not exist in
    titles." 
  end  
/* Otherwise, allow it. */
else
  print "Added! All title_id’s exist in titles."

但在触发器中,您会将没有任何值的插槽(最后插入的)更新为第一个缺失 id 的值。

要发现第一个丢失的 id,您可以执行以下步骤:

  1. 从表中选择 min(id)
  2. 循环递增 id 并从表中选择行。第一个没有行的,是你缺的槽

选项 2

另一种可能性,如Elzo Valugi 所述,是使用增量逻辑构建一个函数,该函数将返回下一个可用插槽并直接在插入时输入。

【讨论】:

  • 您可以使用增量逻辑构建一个函数,该函数将返回下一个可用插槽并直接输入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
相关资源
最近更新 更多