简体   繁体   English

根据另一个表的主键创建主键

[英]Creating primary key based off of a primary key from another table

I have a table that looks like this (only showing a few of the columns as an example), where the ID is being auto incremented: 我有一个看起来像这样的表(仅显示一些列作为示例),其中ID正在自动递增:

 ('client' table) client_id | state | concerns __________|_______|_________ 01 | MA | ... 02 | NJ | ... 03 | MA | ... 

I have another table, and what I want to do for the PK of that table is to create it based on the PK from the 'client' table. 我有另一个表,该表的PK我想根据“客户端”表中的PK创建它。 (A client can be one person, or two) (客户可以是一个人,也可以是两个人)

 ('person' table) person_id | fname | dob | client_id __________|_______|____________|__________ 01A | MA | 1/1/1978 | 01 01B | MA | 2/7/1985 | 01 02 | NJ | 5/17/1983 | 02 03A | MA | 3/12/1970 | 03 03B | MA | 5/23/1987 | 03 

So it will only add the letters to the PK if the client consists of two people (notice how 'person_id' stayed as 02). 因此,如果客户端由两个人组成,则只会将字母添加到PK中(注意“ person_id”如何保持为02)。

How should I go about doing this? 我应该怎么做呢? I'm not sure if having it as '01_1', '01_2' would make it easier than having it look like '01A', '01B', but whichever way makes it easiest would be preferred! 我不确定是否将其设置为“ 01_1”,“ 01_2”会比看起来像“ 01A”,“ 01B”更容易,但是无论哪种方式都会使其更容易使用! Thank you in advance! 先感谢您!

**(I forgot to mention that I'm using MySQL, if that makes a difference!) **(我忘了说我正在使用MySQL,如果有帮助的话!)

You needs to create a foreign key that references to client id, and then make it a primary key. 您需要创建一个引用客户端ID的外键,然后使其成为主键。 I suggest you to create others columns for specific data. 我建议您为其他数据创建其他列。

Here is a sample, I ignored others columns: 这是一个示例,我忽略了其他列:

CREATE TABLE client (
    client_id CHAR(40),
    PRIMARY KEY(client_id),
) ENGINE=INNODB;

CREATE TABLE person (
    client_id CHAR(40),
    person CHAR(40),
    PRIMARY KEY (client_id, person),
    FOREIGN KEY (client_id) REFERENCES client(client_id)
) ENGINE=INNODB;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM