我有一种情况,我会在一张桌子上拥有多对多的关系。这只是一个例子的快速示例。现在它只是一个原始的csv转储到表中。但我想添加一个交叉引用表或约束,以便在我可以查询供应商时。为简洁起见,我只显示两个ID。
我如何将这种关系添加到下面的示例中?我目前正在使用SQLlite,但我计划将其转换为MS服务器或Postgres用于最终表。
global_duns vendor_duns
9581091 53506312
9581091 961273620
79735371 53506312
79735371 79735371
79735371 135962137
这是我到目前为止所尝试的内容:
DROP TABLE IF EXISTS company;
PRAGMA foreign_keys=off;
CREATE TABLE company
(
CompanyId INTEGER PRIMARY KEY NOT NULL,
global_duns_number INTEGER REFERENCES data(global_duns_number),
vendor_duns INTEGER REFERENCES data(vendor_duns),
CONSTRAINT unique_global UNIQUE (global_duns_number),
CONSTRAINT unique_dun UNIQUE (vendor_duns),
CONSTRAINT unique_vendor UNIQUE (global_duns_number, vendor_duns),
CONSTRAINT unique_vendor_reverse UNIQUE (vendor_duns, global_duns_number)
);
INSERT INTO company (global_duns_number, vendor_duns)
SELECT DISTINCT global_duns_number, vendor_duns
FROM data;
PRAGMA foreign_keys=on;
数据是原始csv导入。