MySQL strange error in CREATE … SELECT: ERROR 1062 (23000): Duplicate entry '0' for key 1

StackOverflow https://stackoverflow.com/questions/4304150

  •  29-09-2019
  •  | 
  •  

Pergunta

This is the problematic query (with the intended meaning: pull all entities paired with entity 530 into a new table, with the count of the pairs):

CREATE TEMPORARY TABLE paired (
  entity_id INTEGER PRIMARY KEY,
  numrels INTEGER
)
SELECT I.entity2_id, COUNT(I.relation_id) AS numrels
FROM pairs I
WHERE I.entity1_id = 530 AND I.entity2_id IS NOT NULL
GROUP BY I.entity2_id
;

I interpret the error message:

ERROR 1062 (23000): Duplicate entry '0' for key 1

as the complaint that I am violating primary key's uniqueness. However, I am grouping by that value, which should ensure the uniqueness, right? Then I thought to try this:

CREATE TEMPORARY TABLE paired (
  entity_id INTEGER PRIMARY KEY,
  numrels INTEGER
)
;
INSERT INTO paired
SELECT I.entity2_id, COUNT(I.relation_id) AS numrels
FROM pairs I
WHERE I.entity1_id = 530 AND I.entity2_id IS NOT NULL
GROUP BY I.entity2_id
;

Surprisingly enough, this works without any problems, even though, according to my understanding, the two should be equivalent.

What gives?!?

For reference:

mysql  Ver 14.12 Distrib 5.0.82sp1, for redhat-linux-gnu (x86_64) using readline 5.1
Foi útil?

Solução

Your statements are not equivalent. CREATE ... SELECT creates the columns you mention in the CREATE part of the statement (that is, entity_id and numrels), and in addition creates columns for each column of the SELECT part of the statement. You end up with four columns in your new table. The results of SELECT are inserted into the last two columns. The other columns are filled with their default values, which results in violating the uniqueness of your primary key.

See also http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top