gpt4 book ai didi

MySQL多个表引用相同的外键

转载 作者:行者123 更新时间:2023-11-29 16:35:02 25 4
gpt4 key购买 nike

我有三个这样的表。

location(id,name)

tour(id,name)

hotel(id,name)

上面三个表(位置、旅游和酒店)有很多图片。

所以存储图像的传统方式是

location_images(id,image_url,location_id)

tour_images(id,image_url,tour_id)

hotel_images(id,image_url,hotel_id)

我可以制作一个表来存储所有三种类型的图像,而不是像这样将图像保存在三个不同的表中吗?

images(id,image_url,type,foreign_key)

如何使用 MySQL 实现此目的?

如何使我的 foreign_keytype 连接?

我正在使用 MySQL 5.7.24-0ubuntu0.18.04.1 (Ubuntu)

最佳答案

是的,你可以。

CREATE TABLE images (
id INT PRIMARY KEY AUTO_INCREMENT,
image_url VARCHAR(255) NOT NULL,
image_belongs_to_type ENUM('location', 'tour', 'hotel') NOT NULL,
post_id INT NOT NULL);

当您调用图像时,只需提供带有 ENUM 值的帖子 ID 即可。(地点、行程和酒店)

例如:

select * from images where image_belongs_to_type ='location' and post_id = 'location_id'
select * from images where image_belongs_to_type ='tour' and post_id = 'tour_id'
select * from images where image_belongs_to_type ='hotel' and post_id = 'hotel_id'

ENUM - MySql

关于MySQL多个表引用相同的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53645777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com