Link to home
Start Free TrialLog in
Avatar of arantius
arantius

asked on

MySQL "on delete cascade" doesn't appear to work.

After I set up a test database:

CREATE TABLE hit (
  id int(10) unsigned NOT NULL auto_increment,
  visitorId int(10) unsigned NOT NULL,
  PRIMARY KEY  (id),
  KEY visitorId (visitorId)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO hit (id, visitorId) VALUES
(1, 1),
(2, 2),
(3, 3);

CREATE TABLE visitor (
  id int(10) unsigned NOT NULL auto_increment,
  PRIMARY KEY  (id)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO visitor (id) VALUES
(1),
(2),
(3);

ALTER TABLE hit ADD FOREIGN KEY (visitorId) REFERENCES visitor(id) ON DELETE CASCADE;

I get:

mysql> select * from hit;
+----+-----------+
| id | visitorId |
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         3 |
+----+-----------+
3 rows in set (0.00 sec)

mysql> select * from visitor;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.00 sec)

When I:

mysql> delete from hit where id=2;
Query OK, 1 row affected (0.00 sec)

mysql> select * from hit;
+----+-----------+
| id | visitorId |
+----+-----------+
|  1 |         1 |
|  3 |         3 |
+----+-----------+
2 rows in set (0.00 sec)

mysql> select * from visitor;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.00 sec)

The delete doesn't cascade to the visitor table.  Why not?
ASKER CERTIFIED SOLUTION
Avatar of philipjonathan
philipjonathan
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of arantius
arantius

ASKER

I see.  So, if it's not obvious, I'm recording hits to web pages.  Each hit references multiple separate values like the URL, the visitor that made it, and so forth.  I periodically throw away old hit records (in this case, I'm only interested in about the past week at any time), and I was hoping to use cascade to automatically discard e.g. visitors that don't have any hit records left.

Is there a straightforward way to do this?
Well, I don't think we can use on delete cascade here. Probably what you can do is to periodically check the visitor table and delete records which don't have child records.