SQL中交换一对多关系方向的最佳方法是什么?
好吧,不管出于什么原因,我最终遇到了一种情况,在一对多的情况下,钥匙指向了错误的方向。很明显,它从来没有被用作一对多,只是一对一,现在需要将其中一个扩展为多个,而密钥的存储方式是向后的SQL中交换一对多关系方向的最佳方法是什么?,sql,mysql,relationship,associations,Sql,Mysql,Relationship,Associations,好吧,不管出于什么原因,我最终遇到了一种情况,在一对多的情况下,钥匙指向了错误的方向。很明显,它从来没有被用作一对多,只是一对一,现在需要将其中一个扩展为多个,而密钥的存储方式是向后的 images表有一个target\u id、target\u type和target\u列,这三条信息可以通过任意数量的内容表来识别它。target_type仅引用与图像关联的内容块的表名target_column是用于查找图像的虚拟列(实际上不在内容表中)的名称。这使得任何任意内容都可以有多个关联的图像,每个图
images
表有一个target\u id
、target\u type
和target\u列
,这三条信息可以通过任意数量的内容表来识别它。target_type
仅引用与图像关联的内容块的表名target_column
是用于查找图像的虚拟列(实际上不在内容表中)的名称。这使得任何任意内容都可以有多个关联的图像,每个图像都有不同的名称
当您有一段内容,并希望找到与特定名称相关联的图像时,您可以执行以下操作:
select * from images where target_id = content.id
and target_type = "content"
and target_column = "image";
当您引用某一特定内容时,所有这些信息都可用
相反,我想做的是反转所有这些,这样图像表就不知道引用它的特定内容片段,相反,这个负担由每个内容表承担
到目前为止,我知道我可以在内容表中添加一列,然后从图像表中选择所需的信息:
select id, target_id from images where target_type = "content";
我想做的是将其用作子查询,并对内容表进行大规模更新。这样的事情可能吗
update content set image_id =
(select id from images where target_type = "content") as image_ids where id =
(select target_id from images where target_type = "content") as content_ids;
我知道这是失败的,但我想做一些大规模的目标ID分配回图像ID。这是疯了吗?如何执行此操作?您可以加入图像表以执行更新:
update content inner join images on images.target_id = content.id and
images.target_type = 'content' and images.target_column = 'images'
set content.image_id = images.id
您可能希望使用Mysql多表更新机制。(比照) 在你的情况下,这将是
update
content,
images
set
content.image_id = images.id
where
images.target_id = content.id
and images.target_type = 'content'
and images.target_column = 'images'
我希望这对你有帮助
杰罗姆·瓦格纳