简体   繁体   English

Oracle:为其他两列的唯一组合添加增量ID

[英]Oracle: Add incremental ids for unique combination of two other columns

I have a table which looks like this 我有一张看起来像这样的桌子

Seq ID | Uid | Type | URL

for each Uid I can have multiple Urls for any given type, for example 例如,对于每个Uid我可以为任何给定类型提供多个Urls

Uid 123 can have 5 video urls and 6 image type urls Uid 123可以有5 video urls6 image type urls

I want to insert auto incrementing seq id for each combination of Uid and Type so in the previous example the seq id of uid 123 and type video will go 1,2,3,4,5 for each video url and 1,2,3,4,5,6 for each image type url , and same for all the other uid and type combinations. 我想为UidType每个组合插入自动递增seq id,所以在前面的例子中, uid 123的seq id和类型video将为每个video url 1,2,3,4,51,2,3,4,5,6每个image type url 1,2,3,4,5,6 ,所有其他uidtype组合相同。

I would refrain from trying to store this kind of artificial construct in the database. 我不会试图在数据库中存储这种人工构造。 If needed, it can be generated at query time: 如果需要,可以在查询时生成:

SELECT Uid, Type, URL,
       ROW_NUMBER() OVER(PARTITION BY Uid, Type ORDER BY URL) AS SeqID
    FROM YourTable

Can you just do this in a query? 你能在查询中这样做吗?

select row_number() over (partition by uid, type order by url) as seqID, . . .
from table

You can also do this in an update, for an after-the-fact update: 您还可以在更新中执行此操作,以进行事后更新:

with toupdate as (
     select row_number() over (partition by uid, type order by url) as newseqID, . . .
     from table
)
update toudpate
    set seqID as newseqID

If you want to do it as part of an insert, you'll need to create a trigger to maintain the column values. 如果要将其作为插入的一部分,则需要创建一个触发器来维护列值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM