1

Created a new DB schema / tables and tried to insert values. My insert query as follows

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;

Here i get following error after my first insert query, but second insert query worked fine.;

What im doing wrong here?

Error Code: 1060. Duplicate column name 'Unknown' 

3 Answers 3

1

I'm guessing if you alias your columns differently it will work out:

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;

The second query doesn't crash because the strings are different

You haven't provided an alias for the strings so my reasoning is that MySQL tries to help out by creating an alias from the string, but it creates identical aliases

SQLServer wouldn't let you do this; it would give a error that the column in the subquery needs an alias (and it wouldn't let you declare two column aliases that are the same). Aliases are required for columns in a sub query so that you can unambiguously refer to the columns in an outer query - think about this one:

SELECT x FROM(SELECT 1 as x, 'hello' as x)

What should MySQL show you? 1 or "hello"?

Hence the reason why subquery columns need unique aliases

Sign up to request clarification or add additional context in comments.

Comments

1

You can do you need oly to add column names

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;

Comments

1

When you run this line - SELECT * FROM (SELECT 0,'Unknown', 'Unknown') AS tmp - it's getting confused because it treats the string as a column name. To rectify you can change to;

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.