'How insert value mysql (hard request)

INSERT INTO `table`(
    `name`,
    `user`
)
VALUES(
    'this is name',
    'user id should be here'
);

The problem is that where I have to enter the user id, I must recognize it from another table, BUT if it is not there, then create a user, get its id and insert it into the field. It would be possible to get an ID and paste

INSERT INTO `table`(
    `name`,
    `user`
)
VALUES(
    'this is name',
    (SELECT `id` FROM `users` WHERE `name` = 'test user')
);

But the task is such that if there is no such user, then create it and get an ID... I don't know how do that, help pls MySQL 5.7

INSERT INTO `table`(
    `name`,
    `user`
)
VALUES(
    'this is name',
    (IF((SELECT `id` FROM `positions` WHERE `name` = 'ТЕСТОВАЯ ДОЛЖНОСТЬ'), (SELECT `id` FROM `positions` WHERE `name` = 'ТЕСТОВАЯ ДОЛЖНОСТЬ'), (INSERT INTO `positions` (`name`) VALUES ('ТЕСТОВАЯ ДОЛЖНОСТЬ')))
);

It's not working...



Solution 1:[1]

Your second version can be rewritten as an INSERT INTO ... SELECT:

INSERT INTO yourTable (name, user)
SELECT 'this is name', id
FROM users
WHERE name = 'test user';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Biegeleisen