创建了一个新的数据库模式/表,并尝试插入值。 我的插入查询如下
INSERT INTO `arms`.`lobalarmpriorities`(`id`,`alarmpriority`,`description`)
SELECT * FROM (SELECT 0,'Unknown', 'Unknown') AS tmp
WHERE NOT EXISTS(select id FROM lobalarmpriorities WHERE id = 0) LIMIT 1;
INSERT INTO `arms`.`lobalarmpriorities`(`id`,`alarmpriority`,`description`)
SELECT * FROM (SELECT 1,'T1', 'T1 - critical – staffed') AS tmp
WHERE NOT EXISTS(select id FROM lobalarmpriorities WHERE id = 1) LIMIT 1;
在我的第一个插入查询之后,出现以下错误,但是第二个插入查询工作正常。
我在这里做什么错了?
Error Code: 1060. Duplicate column name 'Unknown'
答案 0 :(得分:1)
我猜如果您对列使用不同的别名,则可以解决该问题:
INSERT INTO `arms`.`lobalarmpriorities`(`id`,`alarmpriority`,`description`)
SELECT * FROM (SELECT 0 as id,'Unknown' as a, 'Unknown' as b) AS tmp
WHERE NOT EXISTS(select id FROM lobalarmpriorities WHERE id = 0) LIMIT 1;
第二个查询不会因为字符串不同而崩溃
您尚未为字符串提供别名,因此我的理由是MySQL试图通过从字符串创建别名来提供帮助,但它会创建相同的别名
SQLServer不允许您这样做;这会导致错误,即子查询中的列需要别名(并且不允许您声明两个相同的列别名)。子查询中的列需要别名,以便您可以明确引用外部查询中的列-考虑以下问题:
SELECT x FROM(SELECT 1 as x, 'hello' as x)
MySQL应该向您显示什么? 1还是“你好”?
因此,子查询列需要唯一别名的原因
答案 1 :(得分:1)
您可以根据需要添加列名称
INSERT INTO `arms`.`lobalarmpriorities`(`id`,`alarmpriority`,`description`)
SELECT * FROM (SELECT 0,'Unknown' test, 'Unknown' test1) AS tmp
WHERE NOT EXISTS(select id FROM lobalarmpriorities WHERE id = 0) LIMIT 1;
答案 2 :(得分:1)
在运行此行-SELECT * FROM (SELECT 0,'Unknown', 'Unknown') AS tmp
-时,会感到困惑,因为它将字符串视为列名。要改正,您可以更改为;
INSERT INTO `arms`.`lobalarmpriorities`(`id`,`alarmpriority`,`description`)
SELECT * FROM (SELECT 0 as id,'Unknown' AS colA, 'Unknown' AS colB) AS tmp
WHERE NOT EXISTS(select id FROM lobalarmpriorities WHERE id = 0) LIMIT 1;