I'm using MariaDB 10.3, and what I'm trying to do is an establishment of a 1-to-n relationship as for example specified here in the section "One-To-Many-Relationship". I'm trying to do so via:
CREATE TABLE test_table (
ID INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
test_value INT NOT NULL DEFAULT ID
);
CREATE TABLE related_table (
ID INT NOT NULL,
message VARCHAR(10) NOT NULL DEFAULT 'hello',
FOREIGN KEY (ID) REFERENCES test_table(test_value)
ON DELETE CASCADE
ON UPDATE RESTRICT
)
The SQL Fiddle Editor etc. fail at the execution of this, with the Error:
Function or expression 'AUTO_INCREMENT' cannot be used in the DEFAULT clause of 'ID'
So I suppose you cannot set the default value of a column equal to another column, if the value of that other column is defined by a function or an expression?
If I then omit the AUTO_INCREMENT
, I get:
Can't create table "fiddle"."related_table" (errno: 150 "Foreign key constraint is incorrectly formed")
So I assume you cannot create FOREIGN KEY constraints based on referenced columns with a default value?
Do you see another possibility to do what I need, which is:
A) When I insert a new record into test_table
and do not provide test_value
, its value should be equal to the primary key of the inserted record, which should be auto-generated.
B) The related_table
's ID
should refer to the test_table
's test_value
as foreign key.
The only workaround I currently see is to:
CREATE TABLE test_table (
ID INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
test_value INT NOT NULL
);
CREATE TABLE related_table (
ID INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
message VARCHAR(10) NOT NULL DEFAULT 'hello',
FOREIGN KEY (ID) REFERENCES test_table(test_value)
ON DELETE CASCADE
ON UPDATE RESTRICT
);
And then, if I insert for example 3 records into test_table
:
- Insert first new record into
test_table
, and grab theLAST_INSERT_ID
. - Update the first record just created by setting the value of
test_value
of it equal to that returnedLAST_INSERT_ID
. - Insert the two remaining records into
test_table
, this time directly with theLAST_INSERT_ID
returned from before as the value oftest_value
. - Insert new record into
related_table
with the value of the returnedLAST_INSERT_ID
as its primary keyID
field.
But this seems overcomplicated. Isn't there a better solution for this usecase?
TRIGGER
will help you implement what you want. If not, you are stuck with using app code or reformulating to use Stored routines.