0

There are already posts, for example this one, which state that "naive" inheritance in SQL, namely using one table per class level, is a common thing. Example

create table parent
( id integer primary key
, more-parent-attributes
);

create table child
( id integer primary key references parent(id) on delete cascade
, more-child-attributes
);

My question is only how to insert a child in an idiomatic ANSI SQL way into the table. The foreign key constraint makes the requirement that we first insert a new row into parent and then a new row into child, using the id of the parent row. I don't know how to do this (get this id) safely and portably, and using only one request. Hint: I'm rather a beginner and don't know imperative SQL programming--just in case there is an obvious imperative solution.

4

3 回答 3

0

You must execute two insert.

The first insert add row in parent table, the second insert add row in the child table.

Two insert operations can be grouped in the same transaction.

To get the correct inserted id in the parent table you must get a select id from parent.

Show below:

Step 1:

INSERT INTO parent (id, more att) values (your ID, other values)

Pay attention about ID value, you can use newid() (Sql server) uuid() (mySql) or autoincremental integer field

Step 2:

You retrieve your key querying your parent table with a functional key.

SELECT id FROM parent where functional_key satisfacted

For example, if I store in my parent table a list of employes, a functional key can be register number.

So your query becomes:

SELECT id FROM parent WHERE register_no = 'YOUR_REGISTER_NUMBER'

Step 3:

INSERT INTO child (id, fk_parent, other fields) values(id, fk_parent, other fields)

The fk_parent field must be valued with the result of Step 2.

In this step you can:

value fk_parent with a variable or you can use a subquery (step 2) in your insert statement.

于 2013-09-06T12:44:02.827 回答
0

我最终做了类似的事情。您需要有一些可识别的数据,您可以将这些数据插入到Parent中以获取Id. 如果您在某种应用程序中使用它,那么您可以使用GUID. 在我的应用程序中,我使用了我知道会产生唯一值的源列的串联。

CREATE TABLE Parent
(
     Id INT IDENTITY NOT NULL PRIMARY KEY
    ,SourceId VARCHAR(50) NOT NULL
);

CREATE TABLE Child
(
     ParentId INT NOT NULL REFERENCES Parent (Id)
    ,Data VARCHAR(20)
);

-- Some procedure inserts the unique value
INSERT INTO Parent (SourceId) VALUES ('UNIQUE VALUE');

-- Another procedure inserts data using the unique value
DECLARE @Id INT;

SELECT @Id = Id FROM Parent WHERE SourceId = 'UNIQUE VALUE';

INSERT INTO Child (ParentId, Data) VALUES (@Id, 'Some Data');
于 2013-09-06T12:53:35.167 回答
0

Scope_Identity() 是您要查找的内容:

DECLARE @Id INT

INSERT INTO parent (more-parent-attributes) values (.....)
SET @Id = Scope_Identity()

INSERT INTO child (parent(id), more-child-attributes) SELECT @Id, ....more-child-attributes

Scope_Identity() 返回同一范围内的标识列。这意味着父键应该是标识列:

id  int IDENTITY(1,1)PRIMARY KEY

我认为这种情况就好像你在决定什么是父密钥 ID,你会为子插入使用相同的 ID。

于 2013-09-06T12:51:18.493 回答