简体   繁体   中英

Insert statement in self-join table

What is the correct statement to make an insert in a table with a self-join?

If I try to make a classic insert I get the error:

Cannot add or update a child row: a foreign key constraint fails

This is my insert query:

insert into mTable(record_name,self_fk,val, note, ref,insert_date, end_date)
    values('processo prova',0,1,'nota di prova', 'az12345', NOW(), NOW());

In your INSERT query, you are referencing to a foreign key (the id 0) that doesn't exist -> constraint fails

I saw in your edits, before you roll it back, your CREATE TABLE script.

The field containing the reference to the parent was created this way :

`id_processo_padre` int(11) NOT NULL DEFAULT '1'

I suggest you to edit this field to make it nullable :

ALTER TABLE `mTable` MODIFY `id_processo_padre` int(11) NULL;

This will allow you to INSERT the first top level parent (or any top level parent)

insert into mTable(record_name, self_fk, ...)
            values('processo prova', NULL, ...);
--                                   ^--^----------This

Test it yourself :

Schema (MySQL v5.7)

CREATE TABLE test
(
  id INT(6) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  parent_id INT(6) NULL,
  someData VARCHAR(255),
  FOREIGN KEY (parent_id) REFERENCES test(id)
);

INSERT INTO test VALUES (default, null, "parent"),
                        (default, 1, "child1_1"),
                        (default, 1, "child1_2"),
                        (default, 3, "child2_2");

Query #1

SELECT t1.*, t2.someData AS "My parent's name" FROM test t1
LEFT JOIN test t2
ON t2.id = t1.parent_id
ORDER BY t1.id ASC;

Output

| id  | parent_id | someData | My parent's name |
| --- | --------- | -------- | ---------------- |
| 1   | null      | parent   | null             |
| 2   | 1         | child1_1 | parent           |
| 3   | 1         | child1_2 | parent           |
| 4   | 3         | child2_2 | child1_2         |

View on DB Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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