INSERT INTO,SELECT DISTINCT - 忽略重复的键条目

时间:2014-05-13 02:02:37

标签: mysql sql select insert-into on-duplicate-key

非常简单......我的songs表包含现有的主键值,其中一些已存在于songsID表的iTunesImport列中。

该命令的要点是将iTunesImport表中的新值添加为songs表中的新条目。

我已经阅读了很多示例,他们说要使用以下语法,唯一的区别是我需要使用SELECT DISTINCT,因为给定songsID有多个实例iTunesImport表中的值。

INSERT INTO songs(ID)
SELECT DISTINCT songsID FROM iTunesImport
WHERE (songsID IS NOT NULL)
ON DUPLICATE KEY UPDATE ID = ID

执行时,它返回0行,songs表没有改变。

以下是我表格中的部分......

songs

ID, varchar(15), Not NULL   
Name, varchar(200), Not NULL    
SongType, varchar(200), NULL    
Description, varchar(1000), NULL
DebutDate, date, NULL
TimeStamp, timestamp, Not NULL

以下行

2nd        2nd Self         Original    NULL    NULL    2014-03-11 18:46:40
3xwide     The Triple Wide  Original    NULL    NULL    2014-03-11 18:46:40
40s        40's Theme       Original    NULL    NULL    2014-03-11 18:46:40
ahab       Ahab             Original    NULL    NULL    2014-03-11 18:46:40
allintime  All in Time      Original    NULL    NULL    2014-03-11 18:46:40

我的iTunesImport

iTunesImport

KEY, int(11), No
albumsID, varchar(7), Yes
songsID, varchar(15), Yes
TrackName, varchar(200), No

此表中还有其他列,但在这种情况下它们无关紧要

13  p013    stew           "Der Bluten Kat"
14  p013    stew           "Der Bluten Kat"
15  p013    stew           "Ocean Billy"
16  p014    tinkles        Miss Tinkle's Overture
17  p014    wws            Women Wine and Song >
18  p014    utopian        Utopian Fir >
19  p014    katstune       Kat's Tune >
20  p014    utopian        Utopian Fir
21  p014    billy          Ocean Billy >
22  p014    blacksabbath   Black Sabbath >
23  p014    warpigs        War Pigs >
24  p014    billy          Ocean Billy
25  p014    pequod         The Pequod >
26  p014    ahab           Ahab >
27  p014    pequod         The Pequod >
28  p014    andy           Andy's Last Beer
29  p014    mulche         Mulche's Odyssey
30  p015    dumpcity       Dump City

2 个答案:

答案 0 :(得分:0)

怎么样:

INSERT INTO songs(ID)
SELECT DISTINCT songsID FROM iTunesImport
WHERE (songsID IS NOT NULL)
AND songsID NOT IN (SELECT ID FROM songs)

答案 1 :(得分:-1)

我以前从未见过你的WHERE条款。你确定它是正确的吗?我认为以下内容更有意义。

  INSERT INTO songs(ID)
  SELECT DISTINCT songsID FROM iTunesImport
  WHERE (NOT ISNULL(songsID))
  ON DUPLICATE KEY UPDATE ID = ID