I would like to have a trigger to perform following operation for inserted records:
# pseudocode
if new.group_id is null
set new.group_id = new.id
else
# don't touch it
end
More clearly: say I have one table with three columns: id
primary key, group_id
int, value
varchar.
When I insert with group_id
like that:
INSERT INTO table(value, group_id) VALUES ('a', 10)
I'd like to have:
id | group_id | value
---+----------+------
1 | 10 | a
but when I omit group_id
:
INSERT INTO table(value) VALUES ('b')
it should be automatically set to the id
of this record:
id | group_id | value
---+----------+------
2 | 2 | b
Is it possible with a trigger? (I know I can update the record after inserting but having the trigger would be nicer.)
This trigger should do what you asked.
It's copied from a very similar example in the MYSQL documentation page.
I am answering here, as in the accepted answer Bill Karwin states:
I have an answer for it - for OP (and the visitors to come), here are few points: You cannot update the table from where the trigger gets invoked, for it you'll get Error 1442:
1.to Update the new row Use
BEFORE INSERT ON
trigger, this way you can update all the fields for the new row, which can be accessible via NEW operator i.e.2.Get auto_increment value before insert:
To sum up - the trigger SQL for 'd be something as following:
I don't know of any way to do this in one statement, even using a trigger.
The trigger solution that @Lucky suggested would look like this in MySQL:
However, there's a problem. In the
BEFORE INSERT
phase, the auto-generatedid
value hasn't been generated yet. So ifgroup_id
is null, it defaults toNEW.id
which is always 0.But if you change this trigger to fire during the
AFTER INSERT
phase, so you have access to the generated value ofNEW.id
, you can't modify column values.MySQL doesn't support expressions for the
DEFAULT
of a column, so you can't declare this behavior in the table definition either. *Update: MySQL 8.0.13 supportsDEFAULT (<expression>)
but the expression still can't depend on an auto-increment value (this is documented).The only solution is to do the
INSERT
, and then immediately do anUPDATE
to change thegroup_id
if it's not set.A trigger seems like overkill in this situation. Simply apply a default.
This works for me
I believe that this will work for you
I have two tables
And here is a trigger on the insert of test b. It checks to see if a_id is null and if it is it inserts 0