CREATE TABLE `vn`.`userPhone` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `userFk` INT(10) UNSIGNED NOT NULL,
  `typeFk` VARCHAR(45) NOT NULL,
  `phone` INT(15) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `UserFK_Phone` (`userFk` ASC, `phone` ASC));


ALTER TABLE `vn`.`userPhone` 
ADD CONSTRAINT `fgnTypeFk`
  FOREIGN KEY (typeFk)
  REFERENCES `vn`.`userPhoneType` (code)
  ON DELETE RESTRICT
  ON UPDATE CASCADE;

ALTER TABLE `vn`.`userPhone` 
ADD CONSTRAINT `fgnUserFk`
  FOREIGN KEY (userFk)
  REFERENCES `account`.`user` (id)
  ON DELETE CASCADE
  ON UPDATE CASCADE;
  
insert into vn.userPhone(userFk,typeFk,phone)
	select id,'PersonalPhone', phone
		from vn.client
        where phone is not null;


insert into vn.userPhone(userFk,typeFk,phone)
	select id,'businessPhone', phone
		from vn.worker
        where phone is not null AND phone > '';

insert into vn.userPhone(userFk,typeFk,phone)
    SELECT 
        `w`.`userFk`,
        'businessPhone',
        `m`.`value` AS `mediaValue`
    FROM
        (((((`postgresql`.`person` `p`
        JOIN `postgresql`.`profile` `po` ON ((`po`.`person_id` = `p`.`person_id`)))
        JOIN `postgresql`.`profile_media` `pom` ON ((`pom`.`profile_id` = `po`.`profile_id`)))
        JOIN `postgresql`.`media` `m` ON ((`m`.`media_id` = `pom`.`media_id`)))
        JOIN `postgresql`.`media_type` `mt` ON ((`mt`.`media_type_id` = `m`.`media_type_id`)))
        JOIN `vn`.`worker` `w` ON ((`w`.`id` = `p`.`id_trabajador`)))
            WHERE
        (`mt`.`name` = 'movil empresa');

insert into vn.userPhone(userFk,typeFk,phone)
    SELECT 
        `w`.`userFk`,
        'personalPhone',
        `m`.`value` AS `mediaValue`
    FROM
        (((((`postgresql`.`person` `p`
        JOIN `postgresql`.`profile` `po` ON ((`po`.`person_id` = `p`.`person_id`)))
        JOIN `postgresql`.`profile_media` `pom` ON ((`pom`.`profile_id` = `po`.`profile_id`)))
        JOIN `postgresql`.`media` `m` ON ((`m`.`media_id` = `pom`.`media_id`)))
        JOIN `postgresql`.`media_type` `mt` ON ((`mt`.`media_type_id` = `m`.`media_type_id`)))
        JOIN `vn`.`worker` `w` ON ((`w`.`id` = `p`.`id_trabajador`)))
            WHERE
        (`mt`.`name` = 'movil personal')