如果关系是一对多的,这里的 a NULL
on theimages.album_id
更合适。在表上定义album_id
及其外键约束时images
,允许NULL
是图像可能没有父相册的信号。这种设计允许一对多的相册到图像,同时也允许孤儿图像。
CREATE TABLE albums (
album_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
othercol VARCHAR()
)
CREATE TABLE images (
image_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
album_id INT NULL,
FOREIGN KEY (album_id) REFERENCES albums (album_id)
)
如果一张图片需要以多对多的关系属于多个相册,则需要在它们之间建立一个表格来关联它们。album_images
当给定图像没有相关行时,这仍然允许孤立。
CREATE TABLE albums (
album_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
othercol VARCHAR()
)
CREATE TABLE images (
image_id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
othercol VARCHAR()
)
/* Link albums to images as many times as necessary */
CREATE TABLE album_images (
album_id INT NOT NULL,
image_id INT NOT NULL,
FOREIGN KEY (album_id) REFERENCES albums (album_id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (image_id) REFERENCES images (image_id) ON DELETE CASCADE ON UPDATE CASCADE,
/* composite key on the two, ensuring uniqueness */
PRIMARY KEY (album_id, image_id)
)