在MySQL中创建和更新列

时间:2018-11-19 09:42:28

标签: mysql mysql-workbench

我需要这段代码来创建一个列,然后将其设置为另一个外键。

我不需要其他代码,出于某些原因,我需要此代码。如何添加代码以修改创建的列并使其成为外键?

-- Actualizando la tabla: action

DELIMITER $$
SET @s = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'action'
AND table_schema = 'ibexsales_dev'
AND column_name = 'company_id'
) > 0,
"SELECT 1",
"ALTER TABLE action ADD company_id INT(11) NOT NULL"
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
$$ DELIMITER ;

我需要添加以下代码:

ALTER TABLE `ibexsales_dev`.`action` 
                    ADD CONSTRAINT `fk_company_id_action` 
                    FOREIGN KEY (`company_id`) REFERENCES company(`company_id`);

我尝试了此方法,但是它不起作用:

) > 0,
"SELECT 1",
"ALTER TABLE action ADD company_id INT(11) NOT NULL",
"    ALTER TABLE `ibexsales_dev`.`action` 
                    ADD CONSTRAINT `fk_company_id_action` 
                    FOREIGN KEY (`company_id`) REFERENCES company(`company_id`); "
));

1 个答案:

答案 0 :(得分:1)

您不会重复ALTER TABLE。单个ALTER TABLE查询可以包含多个更改,以逗号分隔。

) > 0,
"SELECT 1",
"ALTER TABLE action ADD company_id INT(11) NOT NULL,
                    ADD CONSTRAINT `fk_company_id_action` 
                        FOREIGN KEY (`company_id`) REFERENCES company(`company_id`); "
));