如何确保数据库表中只有一行?
I would like to ensure that my MySQL table named "myTable" has one-and-only-one row.
So I need to be able to do Update on this row but obviously Insert and Remove should be not possible.
I am asking this question because of this Stack Overflow answer
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
给您的两个建议,其中一个或两个都可能有效,具体取决于您尝试存储的数据的具体情况:
查看 ENUM 或 SET 约束是否适合您;请注意,它们根据 SQL 模式提供不同级别的强制执行(例如严格)。查看更多信息:
http://dev.mysql.com/ doc/refman/5.0/en/constraint-invalid-data.html
和/或
实现 INSERT、UPDATE 和 DELETE 触发器来控制对数据的访问(您可能希望在之前填充数据)您再次创建这些;这取决于您的场景)
http://dev.mysql.com/doc/ refman/5.0/en/create-trigger.html
Two suggestions for you, one or both which may work depending on the particulars of the data you're trying to store:
See if the ENUM or SET constraints will work for you; note that they offer differing levels of enforcement based on SQL mode (e.g., strict). See more info:
http://dev.mysql.com/doc/refman/5.0/en/constraint-invalid-data.html
AND/OR
Implement INSERT, UPDATE, and DELETE triggers to control access on the data (you may want to populate the data initially before you create these; again, it depends on your scenario)
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
最简单的方法是创建一个只有一个合法值的列,然后声明它
not null unique
。这会强制表的行数不超过,但仍允许零行。如果您需要防止删除唯一的行,请使用不同答案中给出的触发器方法。
The easiest approach is to create a column that only has one legal value, then to declare it
not null unique
.This forces the table to have no more than one row, but still allows zero rows. If you need to prevent the removal of the only row, use the trigger approach given in a different answer.
试试这个:
Try this:
您可以使用表权限(假设一旦您设置了相关权限来阻止插入/删除,并且您不应该再更新权限,但是,任何拥有权限的用户都可以再次覆盖权限)
插入一加-首先只有一条记录
然后通过在 table_priv 列中禁用
INSERT、UPDATE、DROP
来添加权限You can make use on tables privileges (assuming once you have set the relevant privileges to block insert/delete, and you should not update the privileges anymore, however, any user has the privileges can override the privileges again)
insert the one-and-only-one record first
then add in the privileges by disable
INSERT, UPDATE, DROP
in column table_priv如果您的数据库设置为“严格”模式,您可以创建如下表:
If your database is set to 'strict' mode, you can create a table like this one:
您可以使用 IF 语句检查 mySQL。
You can check in mySQL using IF statement.