MySQL多个表引用相同的外键

时间:2018-12-06 06:30:41

标签: mysql foreign-keys

我有三个这样的桌子。

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)

1 个答案:

答案 0 :(得分:0)

是的。

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);

调用图片时,只需为帖子ID提供ENUM值即可。 (位置,旅游和酒店)

例如:

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