如何在两个表之间共享相同的主键? [英] How can I share the same primary key across two tables?

查看:120
本文介绍了如何在两个表之间共享相同的主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本关于 EF4 的书,我遇到了这个问题:

I'm reading a book on EF4 and I came across this problem situation:

所以我想知道如何创建这个数据库,以便我可以按照书中的示例进行操作.

So I was wondering how to create this database so I can follow along with the example in the book.

我将如何使用简单的 TSQL 命令创建这些表?忘记创建数据库,想象它已经存在.

How would I create these tables, using simple TSQL commands? Forget about creating the database, imagine it already exists.

推荐答案

当说表共享相同的主键时,只是表示每个表中有一个同名的字段,都设置为主键.

CREATE TABLE [Product (Chapter 2)](
    SKU varchar(50) NOT NULL,
    Description varchar(50) NULL,
    Price numeric(18, 2) NULL,
    CONSTRAINT [PK_Product (Chapter 2)] PRIMARY KEY CLUSTERED 
    (
        SKU ASC
    )
)

CREATE TABLE [ProductWebInfo (Chapter 2)](
    SKU varchar(50) NOT NULL,
    ImageURL varchar(50) NULL,
    CONSTRAINT [PK_ProductWebInfo (Chapter 2)] PRIMARY KEY CLUSTERED 
    (
        SKU ASC
    )
)

建立关系

ALTER TABLE [ProductWebInfo (Chapter 2)] 
    ADD CONSTRAINT fk_SKU 
    FOREIGN KEY(SKU)
REFERENCES [Product (Chapter 2)] (SKU)

如果表名只是单个单词(也不是关键字),则看起来可能会更简单一些,例如,如果表名只是 ProductProductWebInfo,没有附加 (第 2 章):

It may look a bit simpler if the table names are just single words (and not key words, either), for example, if the table names were just Product and ProductWebInfo, without the (Chapter 2) appended:

ALTER TABLE ProductWebInfo
    ADD CONSTRAINT fk_SKU
    FOREIGN KEY(SKU)
REFERENCES Product(SKU)

这篇关于如何在两个表之间共享相同的主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆