How to copy a row in the same table in MySQL only if the row does not exist?
P粉729518806
P粉729518806 2024-02-21 17:19:58
0
1
354

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粉729518806
P粉729518806

reply all(1)
P粉860897943

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!