USE vn;

ALTER TABLE vn.sectorCollectionSaleGroup DROP FOREIGN KEY IF EXISTS sectorCollectionSaleGroup_FK_1;
ALTER TABLE vn.sectorCollectionSaleGroup DROP FOREIGN KEY IF EXISTS sectorCollectionSaleGroup_FK;

ALTER TABLE vn.sectorCollectionSaleGroup DROP KEY IF EXISTS sectorCollectionSaleGroup_UN;
DELETE 
	FROM sectorCollectionSaleGroup 
	WHERE id NOT IN (
		SELECT * 
			FROM (
				SELECT MIN(id) 
					FROM sectorCollectionSaleGroup 
					GROUP BY saleGroupFk
			) as temp_table
	);
ALTER TABLE vn.sectorCollectionSaleGroup ADD CONSTRAINT UNIQUE KEY (saleGroupFk);

ALTER TABLE vn.sectorCollectionSaleGroup ADD CONSTRAINT FOREIGN KEY (sectorCollectionFk) REFERENCES vn.sectorCollection(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE vn.sectorCollectionSaleGroup ADD CONSTRAINT FOREIGN KEY (saleGroupFk) REFERENCES vn.saleGroup(id) ON DELETE CASCADE ON UPDATE CASCADE;

CREATE OR REPLACE TEMPORARY TABLE tSGD
SELECT saleFk, sgd.id, count(*) n
    FROM vn.saleGroupDetail sgd 
    GROUP BY saleFk 
    HAVING n > 1;

DELETE sgd.*
    FROM vn.saleGroupDetail sgd
        JOIN tSGD ON tSGD.saleFk = sgd.saleFk AND tSGD.id <> sgd.id;

DROP TEMPORARY TABLE tSGD;

ALTER TABLE vn.sectorCollectionSaleGroup ADD CONSTRAINT FOREIGN KEY (saleGroupFk) REFERENCES vn.saleGroup(id) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE vn.saleGroupDetail DROP FOREIGN KEY IF EXISTS saleGroupDetail_FK;
ALTER TABLE vn.saleGroupDetail DROP FOREIGN KEY IF EXISTS saleGroupDetail_FK_1;
ALTER TABLE vn.saleGroupDetail DROP KEY IF EXISTS saleGroupDetail_UN;
ALTER TABLE vn.saleGroupDetail ADD CONSTRAINT FOREIGN KEY (saleFk) REFERENCES vn.sale(id) ON DELETE CASCADE ON UPDATE CASCADE;
	