I am creating a table labeled categories where main catgory(parent column) contains 0 and where subcategory contains the ID of the parent category. I heard it is called Referencing. My question: Do i have this table strucutred properly? Or is there a better way like implementing a traversal tree or similar method?
CREATE TABLE `categories` (
`primary_id` int(11) NOT NULL auto_increment,
`master_id` int(11) NOT NULL default '0',
`name` varchar(50) NOT NULL default '',
PRIMARY KEY (`c_id`)
)
INSERT INTO `categories` (`primary_id`, `master_id`, `name`) VALUES
(1, '0', 'Games'),
(2, '0', 'Technology'),
(3, '0', 'Science'),
(4, '0', 'Pop Culture'),
(5, '0', 'Jobs/Services'),
(6, '0', 'Blogs'),
(7, '1', 'Computer'),
(8, '1', 'Game Console'),
(9, '2', 'Cellphone'),
(10, '2', 'Audio/Video/Photos'),
(11, '2', 'Laptop'),
(12, '2', 'Others >'),
(13, '3', 'Human Body'),
(14, '3', 'Ocean Life'),
(15, '3', 'Plant Life'),
(16, '3', 'Animal Life'),
(17, '4', 'Artist'),
(18, '4', 'Upcoming'),
(19, '5', 'Jobs'),
(20, '5', 'Tutoring'),
(21, '5', 'Seminars'),
(22, '5', 'Haircuts'),
(23, '9', 'Iphone'),
(24, '9', 'Android'),
(25, '9', 'Windows Mobile'),
(26, '11', 'Toshiba'),
(27, '11', 'HP'),
(28, '11', 'Apple'),
If you use the InnoDB engine, you can enforce referential integrity for your tables. That way, you can make sure you never insert a category which does not have matching parent id, cascade delete child categories when you delete the parent, etc. Change your create statement to:
While this strategy works sufficiently well for most cases, you might also want to look at other strategies for implementing tree-like structures and the challenges that come with querying them effectively. See this answer on SO for more information on alternative designs for storing tree-like structures in MySQL.