Hey all i am trying to figure out how to go about inserting a new record using the following query:
SELECT user.id, user.name, user.username, user.email,
IF(user.opted_in = 0, 'NO', 'YES') AS optedIn
FROM
user
LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id
ORDER BY user.id;
My INSERT query so far is this:
INSERT INTO user
SELECT *
FROM user
LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id;
However, i am not sure how to do VALUE('','','','', etc etc) when using left and inner joins.
So what i am looking to do is this:
User table:
id | name | username | password | OptIn
--------------------------------------------------------------------
562 Bob Barker bBarker BBarker@priceisright.com 1
And also the user_permission table
user_id | Permission_id
-------------------------
562 4
UPDATE
So like this?
INSERT INTO user (name, username, password, email, opted_in) VALUES ('Bbarker','Bbarker','blahblahblah','Bbarker@priceisright.com',0);
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(),4);
You have to be specific about the columns you are selecting. If your
usertable had four columnsid, name, username, opted_inyou must select exactly those four columns from the query. The syntax looks like:However, there does not appear to be any reason to join against
user_permissionhere, since none of the columns from that table would be inserted intouser. In fact, thisINSERTseems bound to fail with primary key uniqueness violations.MySQL does not support inserts into multiple tables at the same time. You either need to perform two
INSERTstatements in your code, using the last insert id from the first query, or create anAFTER INSERTtrigger on the primary table.Or using a trigger: