我有一张看起来像这样的表:
国家 + form_ID + Original_form_Id + 目录
country original_form catalog form_id
1 6 42 6
1 7 368 7
1 69 722 69
1 69 1837 697
1 659 2 659
1 666 2 666
original_form_id 和form id 的点:除了国家+original_form-id 去不同目录的情况外,它总是相等的,在这行中的含义:
country original_form catalog form_id
1 69 722 69
1 69 1837 697
我需要从中创建 3 个表。一张表用于所有行 1:1(country+original_form 到目录)、第二个 N:1 和第三个 1:N 案例。意义:
第一桌1:1
country original_form catalog
1 6 42
1 7 368
第二表1:N
country original_form catalog
1 69 722
1 69 1837
第三桌N:1
country original_form catalog
1 659 2
1 666 2
我使用下面的答案实现它,但有重复:
INSERT INTO Mapping_1ToN
(SELECT ot1.Country_id, ot1.original_form_id, ot1.catalog_id, ot1.Local_id
FROM mappingtable ot1
WHERE EXISTS -- Multiple catalogs for same country+form
(
SELECT *
FROM mappingtable ot2
WHERE ot1.country_id = ot2.country_id
AND ot1.original_form_id = ot2.original_form_id
AND ot1.form_id <> ot2.form_id
AND ot1.catalog_id <> ot2.catalog_id
));
INSERT INTO Mapping_NTo1
(SELECT ot1.Country_id, ot1.original_form_id, ot1.catalog_id, ot1.Local_id
FROM mappingtable ot1
WHERE EXISTS -- Multiple forms for same catalog
(
SELECT *
FROM mappingtable ot2
WHERE ot1.country_id = ot2.country_id
AND ot1.original_form_id <> ot2.original_form_id
AND ot1.catalog_id = ot2.catalog_id
));
INSERT INTO Mapping_1To1
(SELECT ot1.Country_id, ot1.original_form_id, ot1.catalog_id, ot1.Local_id
FROM mappingtable ot1
WHERE NOT EXISTS -- form+catalog unique per country
(
SELECT ot2.Country_id, ot2.original_form_id, ot2.catalog_id, ot2.Local_id
FROM mappingtable ot2
WHERE ot1.country_id = ot2.country_id
AND (
(ot1.original_form_id = ot2.original_form_id AND ot1.catalog_id <> ot2.catalog_id AND ot1.form_id = ot2.form_id)
OR
(ot1.original_form_id <> ot2.original_form_id AND ot1.catalog_id = ot2.catalog_id)
)
));