如果它不存在,如何在mysql中插入多行

时间:2017-07-05 07:56:27

标签: mysql sql

我只想同时插入多行。 但我想忽略已经在表格中的每一个。 我只是进行查询,但它有语法问题。 任何人都可以帮我解决吗? 这是我的SQL查询:

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" 
             ) 

1 个答案:

答案 0 :(得分:1)

pageidtargetpageidmediaid列上创建唯一索引并使用INSERT IGNORE语句。
INSERT IGNORE INTO targetmediaid (pageid, targetpageid, mediaid) VALUES ("4578583556", "5633144318", "1544121716250721765_5633144318"), ("4578583556", "5633144318", "1544121605403655131_5633144318"),("4578583556", "5633144318", "1544121513523117304_5633144318") .....等等。