基本上,我需要根据另一个表中列的值更新一个表中的列。这个问题在这里至少被问过几次,每个高票答案都表示加入两个表并根据另一个表中适用列的值设置一个表中列的值:
- SQL update from one Table to another based on a ID match
- Update table based on another table
- How to update table based on another table column?
- Update based on another table result
- how to update table based on another table in mysql?
- how to update table based on another table in mysql?
- Update Relational table based on another table in MySQL
- How to update a column with another tables columns value?
它似乎对我不起作用,要么是我没有看到正确的东西,要么是我的条件不同。
编辑 1。我没有显示它,但是 supertype
也有一个 accounts_id
列,我认为这是我要加入的列。
我有一个父类(super class)型和子类型表,其中子类型表包含一个名为 supertype_id
的第二个字段,它存储父类(super class)型记录的 PK(如下所示的模式)。
我需要根据父类(super class)型的某些其他属性,使用父类(super class)型表的 PK 更新给定子类型记录(即 subtype.id=123
)的 subtype.supertype_id
表(即 supertype.publicId=321
)。
所以,我最初认为我需要某种 JOIN,但是,由于 JOIN 尚不存在,所以没有更新任何行。
UPDATE subtype
INNER JOIN supertype ON supertype.id=subtype.id
SET subtype.supertype_id=supertype.id
WHERE subtype.id=123 AND supertype.idPublic=321;
UPDATE subtype
INNER JOIN supertype ON supertype.id=subtype.id AND supertype.idPublic=321
SET subtype.supertype_id=supertype.id
WHERE subtype.id=123;
我可能会做类似下面的事情,但是,这样做有问题,因为它不同于所有高度投票的答案,它还会尝试将 suptype.supertype_id
设置为 NULL
如果 supertype
没有给定 idPublic
的记录,这将导致外键约束。
UPDATE subtype SET supertype_id = SELECT id FROM superset WHERE idPublic=321;
这应该如何实现?
编辑 2。也许是这样的?
UPDATE suptype sbt
INNER JOIN supertype spt1 ON spt1.id=sbt.id
INNER JOIN supertype spt2 ON spt2.accounts_id=spt1.accounts_id
SET sbt.supertype_id =sbt2.id
WHERE sbt2.idPublic=321 AND sbt.id=123;
CREATE TABLE supertype (
id INT NOT NULL AUTO_INCREMENT,
data VARCHAR(45) NULL,
publicId INT NOT NULL,
PRIMARY KEY (id),
INDEX publicIdIdx (publicId ASC))
ENGINE = InnoDB;
CREATE TABLE subtype (
id INT NOT NULL,
supertype_id INT NOT NULL,
data VARCHAR(45) NULL,
PRIMARY KEY (id),
INDEX fk_subtype_supertype1_idx (supertype_id ASC),
CONSTRAINT fk_subtype_supertype
FOREIGN KEY (id)
REFERENCES supertype (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_subtype_supertype1
FOREIGN KEY (supertype_id)
REFERENCES supertype (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
最佳答案
您需要选择该特定值。如果您有一个配方存储面粉类型作为面粉表中的 id,但是您有一个允许用户选择类型而不是类型 id 的表单,您可以将用户的选择转换为外部表的id 是这样的。
UPDATE TableRecipe
SET BakeMinutes = 90,
FlourTypeID = (SELECT FlourTypeID FROM TableFlourTypes WHERE Type = 'AllPurpose')
WHERE RecipeID= 34
关于mysql - 使用另一个表的主键更新外键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49157393/