Home > database >  Mysql reference table with the reference table is the same table when inserting data problems
Mysql reference table with the reference table is the same table when inserting data problems

Time:10-15



As shown in figure, according to the Course table Cpno is outside the building, the primary key is Cno,
But when inserting data, there is a problem,

the Error Code: 1452. Always add or update a child row: a foreign key constraint fails (` LZX `. ` course `, constraint ` course_ibfk_1 ` foreign key (` Cpno `) REFERENCES ` course ` (` cno `))

Proven findings:
A separate implementation: insert into Course values (' 2 ', 'mathematics', null, 2);
But when all:
Insert into Course values
(' 1 ', 'database', '5' 4),
(' 2 ', 'mathematics', null, 2),
(' 3 ', 'information system', '1', 4),
(' 4 ', 'operating system', '6' 3),
(' 5 ', 'data structure', '7, 4),
(' 6 ', 'data processing, null, 2),
(' 7 ', 'PASCAL language', '6' 4);

Will be an error,

In essentially is possible, could you tell me how to solve your great god?

CodePudding user response:

Table structure is a little bit drunk, must be so, bulk insert, cpno full set to null, insert, update again

CodePudding user response:

Uh huh... The table structure really let a person very drunk, I didn't look wrong you do it yourself constraint... ??
If regardless of the form field intention? Look at the structure of my suggestion as follows:
1. Answer the question is that you first one-time increase new record, for the record (' 1 ', 'database', '5' 4), the database itself is not new (' 5 ', 'data structure', '7, 4) record how through external key limit constraints le?
2. Your restraint column Cpno will appear a Null value, why add restrictions, again?
3. Present, my guess is that this table should be to make course selection and primary class, or whatever the type to use, I suggest to set up a "course selection table", the other to do a table of primary class to use, if necessary, on the outside of the primary schedule set up key points to course selection table, and the resulting associations, such as schedule record to be deleted or change, also can synchronization confirm records in the primary schedule
4. Still need to describe exactly what to do, you will get more precise answer

CodePudding user response:

The simplest way, delete the foreign keys, for small twenty years database, foreign keys that dongdong, do a lot good, don't need to trouble,

CodePudding user response:

Want to ask, if the table is empty, the reference and target table is the same table, there will be no conflict
  • Related