MySQL 不尊重唯一键和主键
嘿。
首先,我不得不说,这是我第一次尝试编写 SQL,这意味着我是一个 n00b。请耐心等待。
现在,我正在尝试在数据库中创建一个名为“push”的表,如下所示:
CREATE TABLE push
(id int NOT NULL AUTO_INCREMENT,
UDID varchar(40) NOT NULL,
token varchar(64) NOT NULL,
lastpost int DEFAULT '0',
PRIMARY KEY(id),
UNIQUE KEY(id, UDID, token));
可以,但不符合预期。如果我现在尝试在此处插入一些值,如下所示:
INSERT INTO push (UDID, token, lastpost)
VALUES ('123456789abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwqyz123456789', 211);
INSERT INTO push (UDID, token, lastpost)
VALUES ('123456789abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwqyz123456789', 211);
在我看来,这会导致错误,因为 UDID 和令牌相等,但它根本不会触发任何错误,它只是插入重复项。
我可能在这里错过了一些东西,但我无法找出是什么。我怎样才能让它返回预期的结果?
谢谢。
Hey.
To start with, I have to say that this is the first time I have ever tried to write SQL, which means I'm a n00b. Have some patience, please..
Now, I'm trying to create a table called "push" in my database like this:
CREATE TABLE push
(id int NOT NULL AUTO_INCREMENT,
UDID varchar(40) NOT NULL,
token varchar(64) NOT NULL,
lastpost int DEFAULT '0',
PRIMARY KEY(id),
UNIQUE KEY(id, UDID, token));
That works, but not as expected. If I now try to insert some values here like this:
INSERT INTO push (UDID, token, lastpost)
VALUES ('123456789abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwqyz123456789', 211);
INSERT INTO push (UDID, token, lastpost)
VALUES ('123456789abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwqyz123456789', 211);
That would, in my eyes, cause an error, because the UDID and token are equal, but it does not trigger any error at all, it just inserts the duplicate.
I might have missed something here, but I can't find out what. How can I make this return the expected result?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
this:
意味着这 3 者的组合应该是唯一的。两行的 id 字段(自动增量)将不同,因此它将满足该规则
如果组合应该是唯一的,请使其不带
id
this:
Means that the combination of those 3 should be unique. The id field (auto-increment) will be different for the 2 rows, so it will satisfy that rule
If the combination should be unique, make it without the
id
此处的此位
可确保您始终可以输入重复的 UDID 值,并且该值将被接受,因为唯一性测试包括
ID
;它被定义为auto_increment
。从此密钥中删除ID
,您应该得到您想要的检查,即This bit here
ensures that you can always enter a duplicate value for UDID, and it will be accepted as the test for uniqeness includes
ID
; which is defined asauto_increment
. RemoveID
from this key and you should have the check you want i.e.如果您希望
UDID
和token
都是唯一的,或者换句话说,不应允许两个 UDID 相同,也不应允许两个令牌相同,请尝试:If you want both
UDID
andtoken
to be unique or in other words no two UDID should be allowed to be the same nor two token should be allowed to be the same, try: