在mysql中创建和更新列

vfh0ocws  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(332)

我需要这段代码来创建一个列,然后使它成为另一个外键。
我不想另一个代码,我需要这是出于某些原因。如何添加代码来修改已创建的列并使其成为外键?

-- 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`); "
));
zpgglvta

zpgglvta1#

你不能重复 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`); "
));

相关问题