mysqlsqlsql-insertinsert-into

Insert into table uid from another table if it is not present in initial table


I am sorry if this may be a duplicate but I have been searching on StackOverflow for a while and can not see anything that exactly fits the query I am looking to do.

Basically, I have a user database that I have recently created options to the users but only for users that were level 1.

Now I am wanting to change that and give options to everyone no matter what their level is.

I am looking to go through all users that are currently in the database and if no options are found in the urights for that user with the relationship of uid=id then insert options using the user id from the user table.

I have been playing with the injection for a while but I just can not seem to get it to work.

Here is a sqlfiddle I have created

My latest 3 queries I have used are:

insert into urights ('', u.id, 1, 1, 0) (SELECT u.id FROM usr u WHERE (SELECT ur.id FROM urights ur WHERE ur.uid != u.id) )

SELECT id FROM usr u (INSERT INTO urights (id, uid, quotes, pos, nmode) VALUES ('', u.id, 1, 1, 0) WHERE uid NOT IN (u.id))

INSERT INTO urights (id, uid, quotes, pos, nmode) VALUES ('', a.id, 1, 1, 0) SELECT a.id FROM usr a WHERE NOT EXISTS (SELECT ur.uid FROM urights ur WHERE AS ur.uid = a.id)

Any pointers in what I am doing wrong and guidance to correcting this is most appreciated :)


Solution

  • Updated answer, this way you still iterate over the user id that aren't present while setting the other values in the same statement.

    INSERT urights (uid, quotes, pos, nmode) 
    SELECT DISTINCT u.usernumber, 1, 1, 0
    FROM usr u
    WHERE
    NOT EXISTS (SELECT uid FROM urights ur
              WHERE ur.uid = u.usernumber);
    

    http://www.sqlfiddle.com/#!9/62b0ff9/1