views:

754

answers:

3

I'm trying to use SQL to delete multiple rows from multiple tables that are joined together.

Table A is joined to Table B Table B is joined to Table C

I want to delete all rows in table B & C that correspond to a row in Table A

CREATE TABLE `boards` (
  `boardid` int(2) NOT NULL AUTO_INCREMENT,
  `boardname` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY  (`boardid`)
);

-- --------------------------------------------------------

-- 
-- Table structure for table `messages`
-- 

CREATE TABLE `messages` (
  `messageid` int(6) NOT NULL AUTO_INCREMENT,
  `boardid` int(2) NOT NULL DEFAULT '0',
  `topicid` int(4) NOT NULL DEFAULT '0',
  `message` text NOT NULL,
  `author` varchar(255) NOT NULL DEFAULT '',
  `date` datetime DEFAULT NULL,
  PRIMARY KEY  (`messageid`)
);

-- --------------------------------------------------------

-- 
-- Table structure for table `topics`
-- 

CREATE TABLE `topics` (
  `topicid` int(4) NOT NULL AUTO_INCREMENT,
  `boardid` int(2) NOT NULL DEFAULT '0',
  `topicname` varchar(255) NOT NULL DEFAULT '',
  `author` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY  (`topicid`)
);
+3  A: 

this can be done by your db-system if you are using foreign keys with "on delete cascade".

Take a look here: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

Bernd Ott
+1  A: 

Well, if you had used InnoDB tables, you could set up a cascading delete with foreign keys that would do it all automatically. But if you have some reason for using MyISAM, You just use a multiple-table DELETE:

DELETE FROM boards, topics, messages
USING boards INNER JOIN topics INNER JOIN messages
WHERE boards.boardid = $boardid
    AND topics.boardid = boards.boardid
    AND messages.boardid = boards.boardid;
Chad Birch
A: 

You could either just check for presence

delete from topics where boardid in (select boardid from boards)
delete from messages where boardid in (select boardid from boards)

but this wolud only make sense if this behaviour should not always apply. When the behaviour should always apply, implement foreign keys with delete on cascade

explained on a zillion sites, in your helpfiles and here

Peter