简体   繁体   中英

How can I delete rows from table connected with foreign key?

I have table Songs with columns(ID_Song, Title, ID_Artist, ID_Image, ID_Audio) where ID_Artist, ID_Image, ID_Audio are foreign key.

Table Artists with columns (ID_Artist, Name) Table Images with columns (ID_Image,filename, extension, size) Table Audios with columns (ID_Audio,filename, extension, size)

Columns songs.ID_Artist references Artists.ID_Artist, songs.ID_Image references Images.ID_Image and songs.ID_Audio references Audios.ID_Audio, so when I delete a row from table Songs I want the data connected with that row from other tables be deleted as well, but I can't because of the foreign key, is there a way to do it?

Table Songs

CREATE TABLE `songs` (
 `ID_Song` int(11) NOT NULL AUTO_INCREMENT,
 `SongTitle` varchar(100) NOT NULL,
 `ID_Artist` int(11) NOT NULL,
 `ID_Img` int(11) NOT NULL,
 `ID_SongFile` int(11) NOT NULL,
 `Approved` tinyint(1) NOT NULL DEFAULT 0,
 PRIMARY KEY (`ID_Song`),
 KEY `ID_Artist` (`ID_Artist`),
 KEY `ID_SongFile` (`ID_SongFile`),
 KEY `ID_Img` (`ID_Img`),
 CONSTRAINT `songs_ibfk_1` FOREIGN KEY (`ID_Artist`) REFERENCES `artists` (`ID_Artist`) ON DELETE CASCADE,
 CONSTRAINT `songs_ibfk_2` FOREIGN KEY (`ID_SongFile`) REFERENCES `files` (`ID_File`) ON DELETE CASCADE,
 CONSTRAINT `songs_ibfk_3` FOREIGN KEY (`ID_Img`) REFERENCES `images` (`ID_Img`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Table Images

CREATE TABLE `images` (
 `ID_Img` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) NOT NULL,
 `extension` varchar(10) NOT NULL,
 `size` float NOT NULL,
 PRIMARY KEY (`ID_Img`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

For the given schema, you need to fetch ID_SongFile and ID_Img before you delete a song. Assuming you want to delete the song with ID=123. In pure SQL it could be:

select ID_SongFile, ID_Img into @file_id, @img_id
from songs
where ID_Song = 123;

delete from songs where ID_Song = 123;

delete from images where ID_Img = @img_id;

delete from files where ID_File = @file_id;

Depending on your data logic, it might be better to "reverse" the relation. If files and images are only related to songs, and it's always a one-to-one relation, I would remove the ID_SongFile and ID_Img columns from the songs table and have a ID_Song column as foreign key in images and files tables. If you define those new FKs with ON DELETE CASCADE , you would just need to delete the song, and the related file and image will "disappear".

You could also just store all image and file information in the songs table. But IMHO having the columns image_name , image_extension , image_size , file_name , file_extension and file_size doesn't look very good. But there is nothing really wrong with that design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM