如何在不同的外键上自动递增? [英] How to auto increment on different foreign keys?

查看:43
本文介绍了如何在不同的外键上自动递增?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 个 SQL 表(表 1、表 2).表 1 具有唯一 ID.表 2 具有表 1 id 的外键.

Lets say I have a 2 SQL tables (table 1, table2). Table 1 has unique IDs. Table 2 has a foreign key to table 1's id.

如何根据该 ID 递增.

How do I increment based on that ID.

示例:

Table 1     Table 2 
 ID           foreign key ID
 1            1           1
 2            1           2
 3            2           1
 4            2           2
              2           3
              3           1
              3           2
              3           3
etc..

创建表的 sql 语法基本上是什么?

Basically what is the sql syntax for the table creation to do this?

推荐答案

您也可以在 Insert 上执行此操作,如下所示:

You could also do it on the Insert, like this:

Insert Table2(ForeignKey, Id)
Select @ForeignKey, 1 + Coalesce(max(Id), 0)
from table2
Where ForeignKey = @ForeignKey

这篇关于如何在不同的外键上自动递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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