我一直在收到错误代码:1060。:
但是,我需要插入一些具有相同值的字段,但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
我的专栏:
请帮助,谢谢。
答案 0 :(得分:8)
您的重复列名称来自您的子查询。您多次选择null
,john
和2016-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
是否有用,您只选择可能插入的单行。
答案 1 :(得分: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
没有做任何事情,因为你只有一行。