2016-08-04 76 views
1

我已經收到錯誤代碼:1060:錯誤代碼:1060重複列名

  • 重複列名「NULL」
  • 重複的列名「2016年8月4日01: 25:06'
  • 重複的列名‘約翰’

不過,我需要插入一些字段的值相同,但SQL否認,並表示對上述錯誤。這個錯誤可能是sql無法選擇相同的列名,在這種情況下是否有其他編寫代碼的方式?下面是我當前的代碼

INSERT INTO test.testTable SELECT * 
FROM (SELECT NULL, 'hello', 'john', '2016-08-04 01:25:06', 'john' 
, '2016-08-04 01:25:06', NULL, NULL) AS tmp 
WHERE NOT EXISTS (SELECT * FROM test.testTable WHERE message= 'hello' AND created_by = 'john') LIMIT 1 

我的專欄:

  • (ID,消息,CREATED_BY,CREATED_DATE,updated_by,updated_date,DELETED_BY,deleted_date)

請幫助,謝謝。

回答

1

您的重複列名來自您的子查詢。您多次選擇nulljohn2016-08-04 01:25:06。爲您提供與名稱/別名選擇列:

INSERT INTO test.testTable 
SELECT * 
FROM (SELECT NULL as col1, 'hello' as col2, 
     'john' as col3, '2016-08-04 01:25:06' as col4, 
     'john' as col5, '2016-08-04 01:25:06' as col6, 
     NULL as col7, NULL as col8) AS tmp 
WHERE NOT EXISTS (SELECT * 
        FROM test.testTable 
        WHERE message= 'hello' AND created_by = 'john') 
LIMIT 1 

不知道limit 1在這裏很有用,你只能選擇一個單行潛在插入。

+0

嗨,非常感謝,問題解決了 – nicker

+0

@nicker - 很高興幫助 – sgeddes

1

您正在使用子查詢。由於您不提供列別名,因此MySQL必須爲您選擇別名 - 並選擇用於定義的公式。

您可以編寫查詢,而不子查詢:

INSERT INTO test.testTable(. . .) 
    SELECT NULL, 'hello', 'john', '2016-08-04 01:25:06', 'john', 
      '2016-08-04 01:25:06', NULL, NULL 
    FROM dual 
    WHERE NOT EXISTS (SELECT 1 
         FROM test.testTable tt 
         WHERE tt.message = 'hello' AND tt.created_by = 'john' 
        ); 

如果你在SELECT使用子查詢,然後使用相關的條款在WHERE子查詢:

INSERT INTO test.testTable(. . .) 
    SELECT * 
    FROM (SELECT NULL as col1, 'hello' as message, 'john' as created_by, 
       '2016-08-04 01:25:06' as date, 'john' as col2, 
       '2016-08-04 01:25:06' as col3, NULL as col4, NULL as col5 
     ) t 
    WHERE NOT EXISTS (SELECT 1 
         FROM test.testTable tt 
         WHERE tt.message = t.message AND 
          tt.created_by = t.created_by 
        ); 

此外, LIMIT 1沒有做任何事,因爲你只有一行。

+0

嗨,感謝您指出並解決了問題。非常感謝 – nicker