MySQL 类似断言的约束
我是MySQL新手,我刚刚发现它不支持断言。
我得到了这张桌子:
CREATE TABLE `guest` (
`ssn` varchar(16) NOT NULL,
`name` varchar(200) NOT NULL,
`surname` varchar(200) NOT NULL,
`card_number` int(11) NOT NULL,
PRIMARY KEY (`ssn`),
KEY `card_number` (`card_number`),
CONSTRAINT `guest_ibfk_1` FOREIGN KEY (`card_number`) REFERENCES `member` (`card_number`)
)
我需要的是一个会员最多可以邀请2位客人。 因此,在表 guest
中,我需要特定的 card_number
最多可以出现 2 次。
我怎样才能在没有断言的情况下管理它?
谢谢。
I'm a MySQL newbie, I just discovered that it doesn't support assertions.
I got this table:
CREATE TABLE `guest` (
`ssn` varchar(16) NOT NULL,
`name` varchar(200) NOT NULL,
`surname` varchar(200) NOT NULL,
`card_number` int(11) NOT NULL,
PRIMARY KEY (`ssn`),
KEY `card_number` (`card_number`),
CONSTRAINT `guest_ibfk_1` FOREIGN KEY (`card_number`) REFERENCES `member` (`card_number`)
)
What I need is that a member can invite maximum 2 guests.
So, in table guest
I need that a specific card_number
can appear maximum 2 times.
How can I manage it without assertions?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这绝对是表“guest”上的 BEFORE INSERT 触发器的味道:
这基本上会查找当前的客人计数,如果它已经 >=2,则将 card_number 设置为 NULL。由于card_number被声明为NOT NULL,这将拒绝插入。
在 MySQL 5.1.41-3ubuntu12.10 (Ubuntu Lucid) 上测试并适用于我
This definitly smells of a BEFORE INSERT trigger on the table 'guest':
This basically looks up the current guest count, and if it is already >=2 sets card_number to NULL. Since card_number is declared NOT NULL, this will reject the insert.
Tested and works for me on MySQL 5.1.41-3ubuntu12.10 (Ubuntu Lucid)