简体   繁体   English

如何在MySQL中为两个单独的表创建自动增量ID字段?

[英]How to create auto increment ID field for two separate tables in MySQL?

I have two tables (A and B) and I want each record in these tables to have an unique ID (id_C). 我有两个表(A和B),并且我希望这些表中的每个记录都具有唯一的ID(id_C)。 How do I do that? 我怎么做?

TABLE_A:

id_A | id_C
 1      1
 2      3

TABLE_B:

id_B | id_C
 1      2
 2      4

PS. PS。 I was thinking about something like this: 我在想这样的事情:

create table c(
    id_c int not null auto_increment,
    PRIMARY KEY(id_c)
);

create table a(
    id_a int not null auto_increment,
    a_c  int not null,
    PRIMARY KEY(id_a),
    FOREIGN KEY (a_c) REFERENCES c(id_c)
);

create table b(
    id_b int not null auto_increment,
    b_c  int not null,
    PRIMARY KEY(id_b),
    FOREIGN KEY (b_c) REFERENCES c(id_c)
);

Create a table which contains your IDs and make it an auto-incrementing primary key. 创建一个包含您的ID的表,并使其成为自动递增的主键。 Use this table to generate unique ids and reference them with foreign key constraints from the other tables. 使用此表生成唯一的ID,并使用其他表中的外键约束引用它们。 I think this is what you suggested in your question. 我认为这就是您在问题中提出的建议。

Another alternative is to use a GUID . 另一种选择是使用GUID

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

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