If you are using InnoDB, you should look into Foreign Key Constraints which take care of this for you by using the ON DELETE CASCADE
option when you are setting your foreign key relationships.
An example from the docs:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE) ENGINE=INNODB;
With that in place, if you were to do add a parent and a matching child row like this:
INSERT INTO parent (id) VALUES (1);
INSERT INTO child (id, parent_id) VALUES (1,1);
And then removed the parent like this:
DELETE FROM parent WHERE id = 1;
You will find the matching child record to be gone. This is, in my opinion, the best way to do it.
EDIT: To do this within 1 table, you would do something like this:
CREATE TABLE parent (
id INT NOT NULL,
name varchar(250) not null,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB
Then if you add two rows, one referencing the other:
INSERT INTO parent (id,name,parent_id)
VALUES ('1', 'Test 1', NULL), ('2', 'Test 2', '1')
Then delete the parent row of the two:
DELETE FROM parent WHERE id = 1;
You will find that it deletes the child row with parent_id
of 1.