如何解决MariaDb中的重复列名错误

时间:2019-10-16 08:31:14

标签: mysql mariadb

我正在尝试在HeidiSQL中运行以下查询-

INSERT INTO entities (id, name, description, port) SELECT * FROM 
(SELECT 1, 'customer', 'Customer', 'xyz') AS tmp 
WHERE NOT EXISTS 
( SELECT name FROM entities WHERE name = 'customer' AND port = 'xyz' ) LIMIT 1

如果不存在,我想在entities表中插入以上值。 但是我收到这个错误- Duplicate column name 'Customer'

任何想法如何解决这个问题? 感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

向查询的选择区域添加别名:

INSERT INTO entities (id, name, description, port) SELECT * FROM 
(SELECT 1, 'customer' as name, 'Customer' as description, 'xyz') AS tmp 
WHERE NOT EXISTS 
( SELECT name FROM entities WHERE name = 'customer' AND port = 'xyz' ) LIMIT 1

但是,我宁愿在name - port字段上创建唯一索引,以防止创建重复的记录。

答案 1 :(得分:0)

尝试以下操作(请注意,“ id”列是主键):

INSERT INTO entities (name, description, port) 
SELECT 'customer', 'Customer', 'xyz' FROM entities 
WHERE name NOT IN ( SELECT name FROM entities WHERE name = 'customer' AND port = 'xyz' ) LIMIT 1