[英]Foreign key Check constraints in table attribute
I am trying to set an attribute in an SQL table that is made up of a partial id that is designated by user input and part foreign key. 我正在尝试在由用户输入和部分外键指定的部分ID组成的SQL表中设置属性。 For example: The employee will have a 8 character long id, the first 4 digits is the part the user will input and the last 4 characters will reference the branch table to use the branch id.
例如:员工将有一个8个字符长的ID,前4位数字是用户要输入的部分,后4个字符将引用分支表以使用分支ID。
It looks like I need to use a CHECK constraint in order to do this, but I am unsure as to how to enforce the second part of the attribute value to ensure it is in the other table. 看来我需要使用CHECK约束才能执行此操作,但是我不确定如何强制执行属性值的第二部分以确保它在另一个表中。
I am hoping thq question is phrased correctly as I am still learning SQL. 我希望这个问题的措词正确,因为我仍在学习SQL。
It looks like I need to use a CHECK constraint in order to do this, but I am unsure as to how to enforce the second part of the attribute value to ensure it is in the other table.
看来我需要使用CHECK约束才能执行此操作,但是我不确定如何强制执行属性值的第二部分以确保它在另一个表中。
In order to "look" into the other table, you'd need to use a SELECT statement within the CHECK constraint. 为了“查看”另一个表,您需要在CHECK约束内使用SELECT语句。 As far as I know, most SQL dbms won't let you do that.
据我所知,大多数SQL dbms不允许您这样做。 (Failing that, standard SQL would use an assertion; I'm not sure any SQL dbms supports assertions yet.)
(否则,标准SQL将使用断言;我不确定是否有任何 SQL dbms支持断言。)
Instead, use two columns--one for the four characters the user supplies, and one for the last four characters representing the branch. 而是使用两列-一列用于用户提供的四个字符,一列用于表示分支的最后四个字符。 You can (and should) use
您可以(并且应该)使用
The behavioral guarantees that the foreign key constraint gives you are important. 外键约束给您的行为保证很重要。 They guarantee that whatever value you use for branch_id in your new table will exist in the table of branches, and that if a used branch_id ever changes, that change will also be recorded in your new table.
它们保证分支表中将存在新表中用于branch_id的任何值,并且如果使用的branch_id发生更改,则该更改也将记录在新表中。 (If you cascade updates.) And you don't get these guarantees if you bundle the two values into a single column.
(如果层叠更新。)如果将两个值捆绑到单个列中,则不会获得这些保证。
the last 4 characters will reference the branch table to use the branch id.
后4个字符将引用分支表以使用分支ID。
You can copy the branch id that way, but you can't reference it. 您可以通过这种方式复制分支ID,但不能引用它。 Reference is a technical term in database design;
参考是数据库设计中的技术术语。 it has to do with foreign key references.
它与外键引用有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.