问题描述
我想限制 SQL 表中的列值.例如,列值只能是car"或bike"或van".我的问题是你如何在 SQL 中实现这一点,在数据库端这样做是个好主意还是应该让应用程序限制输入.
I would like to restrict a column value in a SQL table. For example, the column values can only be "car" or "bike" or "van". My question is how do you achieve this in SQL, and is it a good idea to do this on the DB side or should I let the application restrict the input.
我还打算在未来添加或删除更多值,例如卡车".
I also have the intention to add or remove more values in the future, for example, "truck".
我使用的数据库类型是 SQLite 和 MySQL.
The type of Databases I am using are SQLite and MySQL.
推荐答案
添加一个包含这些传输方式的新表,并使您的列成为该表的外键.将来可以将新的传输方式添加到表中,并且您的列定义保持不变.
Add a new table containing these means of transport, and make your column a foreign key to that table. New means of transport can be added to the table in future, and your column definition remains the same.
通过这种结构,我肯定会选择在数据库级别而不是应用程序级别对其进行规范.
With this construction, I would definitively choose to regulate this at the DB level, rather than that of the application.
这篇关于如何限制 SQLite/MySQL 中的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!