2

这是有问题的查询(具有预期的含义:将与实体 530 配对的所有实体拉入一个新表中,并带有对的计数):

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
;

我解释错误消息:

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

作为我违反主键唯一性的投诉。但是,我按该值分组,这应该确保唯一性,对吗?然后我想试试这个:

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
;

令人惊讶的是,这没有任何问题,尽管根据我的理解,两者应该是等价的。

是什么赋予了?!?

以供参考:

mysql  Ver 14.12 Distrib 5.0.82sp1, for redhat-linux-gnu (x86_64) using readline 5.1
4

1 回答 1

4

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

于 2010-11-29T13:43:31.787 回答