zoukankan      html  css  js  c++  java
  • Can a foreign key be NULL and/or duplicate?

    Can a foreign key be NULL and/or duplicate?

    问题

    Please clarify two things for me:

    1. Can a Foreign key be NULL?
    2. Can a Foreign key be duplicate?

    As fair as I know, NULL shouldn't be used in foreign keys, but in some application of mine I'm able to input NULL in both Oracle and SQL Server, and I don't know why.

    回答1

    Short answer: Yes, it can be NULL or duplicate.

    I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.

    Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.

    Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.

    Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK. 

    回答2

    1 - Yes, since at least SQL Server 2000.

    2 - Yes, as long as it's not a UNIQUE constraint or linked to a unique index.

  • 相关阅读:
    Ocelot + IdentityServer4 坑自己
    撸一个简易商城
    visual studio2013负载测试简单问题记录
    Jquery简单动画的实现记录
    Jquery的一些简单使用记录
    图片变灰css3
    Jquery的一些取值
    ASP.NET WebApi 简单记录
    iframe的一些简单记录
    Jquery Select 下拉框处理
  • 原文地址:https://www.cnblogs.com/chucklu/p/14971656.html
Copyright © 2011-2022 走看看