Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 关联最佳模式_Sql_Jpa 2.0 - Fatal编程技术网

Sql 关联最佳模式

Sql 关联最佳模式,sql,jpa-2.0,Sql,Jpa 2.0,我有一个关于sql关系概念的问题。我有一个简单的例子。 一个餐桌上的人,一个国家,我想记录下这个人曾经生活过的历史 CREATE TABLE person ( person_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT ); CREATE TABLE country ( country_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT ); 第一个解决方案: create table person_l

我有一个关于sql关系概念的问题。我有一个简单的例子。 一个餐桌上的人,一个国家,我想记录下这个人曾经生活过的历史

CREATE TABLE person
(
    person_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE country
(
    country_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT
);
第一个解决方案:

create table person_live_country
(
    plc_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    person_id INT UNSIGNED NOT NULL,
    country_id INT UNSIGNED NOT NULL,
    FOREIGN KEY (person_id) REFERENCES person (person_id),
    FOREIGN KEY (country_id) REFERENCES country (country_id)
);
create table person_live_country
(
    person_id INT UNSIGNED NOT NULL,
    country_id INT UNSIGNED NOT NULL,
    PRIMARY KEY (person_id, country_id),
    FOREIGN KEY (person_id) REFERENCES person (person_id),
    FOREIGN KEY (country_id) REFERENCES country (country_id)
);
第二种解决方案:

create table person_live_country
(
    plc_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    person_id INT UNSIGNED NOT NULL,
    country_id INT UNSIGNED NOT NULL,
    FOREIGN KEY (person_id) REFERENCES person (person_id),
    FOREIGN KEY (country_id) REFERENCES country (country_id)
);
create table person_live_country
(
    person_id INT UNSIGNED NOT NULL,
    country_id INT UNSIGNED NOT NULL,
    PRIMARY KEY (person_id, country_id),
    FOREIGN KEY (person_id) REFERENCES person (person_id),
    FOREIGN KEY (country_id) REFERENCES country (country_id)
);
最好的模式是什么:概念、性能、方便将来我想用JPA映射表。


谢谢。

虽然第二种解决方案已经足够,而且稍微节省空间,但出于以下原因,我推荐第一种解决方案:

  • 如果您希望在将来扩展表设计,例如在
    person\u live-country
    表中添加
    fromdate
    todate
    克隆,则第二个解决方案中的Composite主键将不再起作用。同一个人一生中可以在同一个国家生活不止一次
  • 如果需要将另一个表中的
    person\u live-country
    表作为外键引用,则第一个解决方案更容易