has_table键的日期

时间:2016-08-12 17:51:46

标签: sql database postgresql postgresql-9.1

我有这个架构

-- Create tables section -----------------------------------------

-- Table t1
CREATE TABLE "t1"(
"id" Serial NOT NULL,
PRIMARY KEY ("id");

-- Table t2
CREATE TABLE "t2"(
"id" Serial NOT NULL,
PRIMARY KEY ("id");

-- Table t1_has_t2
CREATE TABLE "t1_has_t2"(
"t1_id" Integer NOT NULL,
"t2_id" Integer NOT NULL,
"d_start" Date,
"d_end" Date,
PRIMARY KEY ("t1_id","t2_id"),
FOREIGN KEY ("t1_id") REFERENCES "t1" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ("t2_id") REFERENCES "t2" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION);

我需要使用表“t1_has_t2”来保存t1或t2期间。例如,我想将此记录保存在表“t1_has_t2”中:

+-------+-------+------------+------------+
| t1_id | t2_id | d_start    | d_end      |
+-------+-------+------------+------------+
| 1     | 1     | 01-01-2016 | 31-01-2016 |
+-------+-------+------------+------------+
| 1     | 1     | 01-02-2016 | 31-12-9999 |
+-------+-------+------------+------------+

如果日期不同,我不知道如何对我的数据库添加具有相同ID的其他记录。

1 个答案:

答案 0 :(得分:1)

问题是表t1_has_t2中的主键仅包含t1_idt2_id。您还应该在主键中包含其余两列以使其正常工作。

顺便提一下,当您使用两个日期时,最好使用daterange列,因为您可以使用EXCLUDE constraint && operator轻松检查重叠。