开发者

The way to extract group of records which want to delete from multi-table and pass back to PHP in MySQL?

I have tow tables which have records want to delete at the same time.

E.g:

table user_files

user_id  file_id[CHAR]
1        F1
1        F2
1        F4
2        F3
2        F4

table files

file_id
    F1
    F2
    F3
    F4

And I want to delete records from files and user_files which has only one user took it.In another words. If there was only one user got this file,E.g:

in user_files there are tow user 1 and 2 and only file F1 and F2 and F3 were took by one user.And ,I want to delete the records base on user_id

    1  F1
    1  F2

from the user_files
and 

    F1
    F2

from the files will be delete at the same time.

The way I did :

SELECT @file_id:=file_id AS file_id,COUNT(file_id) AS cfi FROM `user_files` AS UF 
WHERE file_id IN (SELECT file_id FROM `user_files`开发者_如何学运维 WHERE user_id = 1)
GROUP BY file_id
HAVING cfi = 1;
DELETE `user_files`,`files` FROM `user_files`,`files`
WHERE user_files.file_id= files.file_id AND user_files.`file_id` IN(@file_id); 

The SQL query problem was it only delete the last one record.I mean,the variable @file_id got multi-file_id but only last file_id was delete from both table.

And I did it in this way [ pass file_id into the variable @file_id ] was want to pass the records which want to delete back to user to display which records had been delete.

Thank you very much for any suggestion!


As far as i understand your problem ,you want to delete two records simultaneously from two teble referenced with same user_id

first change your table engine to InnoDB and then apply a foreign key constraint like this

ALTER TABLE `files` ADD FOREIGN KEY ( `file_id` ) REFERENCES `user_files` (
`file_id`
) ON DELETE CASCADE ON UPDATE CASCADE ;

now if you delete any file from first table then that file name will automatically delted from second table.

hope this one helps you. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜