如何设置alter table add列,其条件如下所示。 添加有关员工拥有的爱好的信息;一个员工拥有一个或多个爱好,一个业余爱好被零个或多个员工拥有
如何设置alter table以添加具有此类条件的列?对不起,我还是sql查询条件的新手。
答案 0 :(得分:1)
为了您的解释,我这样做了: 你必须创建3个表,这是一个多对多的关系,即一个有几个爱好和爱好的员工可以是各种各样的员工。一张员工,其他爱好和其他两个外键的表格。
CREATE TABLE `employees` (
`id_employees` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id_employees`));
CREATE TABLE `hobbies` (
`id_hobbies` INT NOT NULL AUTO_INCREMENT,
`name` INT NULL,
PRIMARY KEY (`id_hobbies`));
CREATE TABLE `employees_hobbies` (
`id_employees_hobbies` INT NOT NULL AUTO_INCREMENT,
`id_employees` INT NOT NULL,
`id_hobbies` INT NOT NULL,
PRIMARY KEY (`id_employees_hobbies`),
INDEX `fk_employees_hobbies_1_idx` (`id_employees` ASC),
INDEX `fk_employees_hobbies_2_idx` (`id_hobbies` ASC),
CONSTRAINT `fk_employees_hobbies_1`
FOREIGN KEY (`id_employees`)
REFERENCES `employees` (`id_employees`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_employees_hobbies_2`
FOREIGN KEY (`id_hobbies`)
REFERENCES `hobbies` (`id_hobbies`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
如果您已经有表并希望更改它们,
ALTER TABLE employees_hobbies ADD id_employees INT NOT NULL;
ALTER TABLE employees_hobbies ADD id_hobbies INT NOT NULL;
ALTER TABLE employees_hobbies ADD CONSTRAINT `fk_employees_hobbies_1`
FOREIGN KEY (`id_employees`)
REFERENCES `employees` (`id_employees`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE employees_hobbies ADD CONSTRAINT `fk_employees_hobbies_2`
FOREIGN KEY (`id_hobbies`)
REFERENCES `hobbies` (`id_hobbies`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
您可以使用ADD
修改现有列,而不是MODIFY
。
检查下面的来源。
字体: Alter Table