简体   繁体   English

数据库中没有主键的表?

[英]Table without primary key in DB?

I have 4 tables in DB, and they are regularly connected.我在数据库中有 4 个表,它们定期连接。 Now i have to make new table without new primary key, but it must have foreighn key from other table.现在我必须创建没有新主键的新表,但它必须有来自其他表的外键。

Is it possible?是否可以?

if your relationship from your new table to other table is one to one, the foreign key can be used as your primary key.如果您的新表与其他表的关系是一对一的,则可以将外键用作主键。 otherwise you will need a single or composite primary key to avoid redundancy of rows.否则您将需要单个或复合主键以避免行冗余。

Yes.是的。 To do this you need an index on the column involved in the foreign key.为此,您需要在外键中涉及的列上建立索引。 But it need not be a unique index.但它不必是唯一索引。

Note this.请注意这一点。 Primary keys, and all indexes, can have multiple columns in them.主键和所有索引可以有多个列。 If your new table is a so-called join table showing many-to-many relationships between rows of two other tables, you can create a primary key from both columns.如果您的新表是所谓的连接表,显示了其他两个表的行之间的多对多关系,您可以从两列创建主键。 For example, if you have a student table with the primary key student_id , and a teacher table with the primary key teacher_id , you could create a table like this.举例来说,如果你有一个student用表的主键student_id ,和teacher用表的主键teacher_id ,您可以创建这样的表。

CREATE TABLE student_teacher (
    student_id INT NOT NULL,
    teacher_id INT NOT NULL,
    PRIMARY KEY (student_id, teacher_id),
    UNIQUE INDEX teacher_student (teacher_id, student_id)
)

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

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