简体   繁体   中英

how to insert multi-row in mysql if it's not exist

I just want to insert multi-row at same time. but I want to ignore each one that already in table. I just make query but It had a syntax problem. Any one can help me to solve it? here is my sql query:

INSERT INTO `targetmediaid` (`pageid`, `targetpageid`, `mediaid`) 
SELECT "4578583556", "5633144318", "1544121716250721765_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1544121605403655131_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1544121513523117304_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1544121293112402936_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1544121119770209275_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1544121021170710600_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1544120871450810242_5633144318"  UNION 
SELECT "4578583556", "5633144318", "1542556083004139499_5633144318"  as t 
WHERE NOT EXISTS
   ( SELECT `pageid`, `targetpageid`, `mediaid` 
       FROM `targetmediaid` 
      WHERE `mediaid` 
         IN  ("1544121716250721765_5633144318" , 
              "1544121605403655131_5633144318" , 
              "1544121513523117304_5633144318" , 
              "1544121293112402936_5633144318" , 
              "1544121119770209275_5633144318" , 
              "1544121021170710600_5633144318" , 
              "1544120871450810242_5633144318" , 
              "1542556083004139499_5633144318" 
             ) 

Create a unique index on pageid , targetpageid , mediaid columns and use INSERT IGNORE statement.
INSERT IGNORE INTO targetmediaid (pageid, targetpageid, mediaid) VALUES ("4578583556", "5633144318", "1544121716250721765_5633144318"), ("4578583556", "5633144318", "1544121605403655131_5633144318"),("4578583556", "5633144318", "1544121513523117304_5633144318") ..... and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM