search

Home  >  Q&A  >  body text

How to copy a row in the same table in MySQL only if the row does not exist?

I'm trying to figure out how to copy a row record from the same table (only if the row doesn't exist), but the solutions I found are only partial. For example, "Copy record" or "Insert if not present." So I tried to merge these answers to make my answer, but... I guess I just made some disgusting code.

Let’s take a look at this

INSERT INTO LCL
SELECT * FROM LCL WHERE (UID = 0 AND NAME = 'S_TYPE')
WHERE NOT EXISTS (SELECT * FROM LCL WHERE UID = 11 AND NAME = 'S_TYPE' LIMIT 1);

There is a default format record, UID = 0. If there is no record with NAME = S_TYPE, copy the record with NAME = S_TYPE AND UID = 0 and change UID to 11. The record should copy the data for all columns. So I tried using SELECT * but not sure if it is correct.

I'm sure I screwed up both WHEREs...

P粉729518806P粉729518806321 days ago458

reply all(1)I'll reply

  • P粉860897943

    P粉8608979432024-02-22 11:55:57

    If you already have WHERE then the follow up should be AND. I don't think you really need the brackets on the first WHERE:

    INSERT INTO LCL
    SELECT * FROM LCL 
     WHERE UID = 0 AND NAME = 'S_TYPE'
       AND NOT EXISTS (SELECT * FROM LCL WHERE UID = 11 AND NAME = 'S_TYPE' LIMIT 1);

    reply
    0
  • Cancelreply