I am trying to fabricate an SQL query that will provide these results:
| Category Title | Subcategory Of |
-----------------------------------
| Category 1 | |
| Category 2 | |
| Category 3 | |
| Category 4 | |
| Category 5 | |
| Category 6 | Category 4 |
| Category 7 | Category 5 |
This is what my database looks like:
CREATE TABLE `categories` (
`category_id` int(4) NOT NULL AUTO_INCREMENT,
`subcategory_id` int(4) NOT NULL,
`category_title` longtext COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `categories` (`category_id`, `subcategory_id`, `category_title`) VALUES
(1, 0, 'Category 1'),
(2, 0, 'Category 2'),
(3, 0, 'Category 3'),
(4, 0, 'Category 4'),
(5, 0, 'Category 5'),
(6, 4, 'Category 6'),
(7, 5, 'Category 7');
I thought that you would use JOIN, but I wasn’t able to mentally think of what kind of query to run, since as far as I knew JOIN was for joining two tables, not two columns. I’m new to these advanced queries (I’m good with INSERT, UPDATE, DELETE, etc. though). Any help is appreciated.
This is what I was trying, which makes no sense really.
SELECT * FROM categories RIGHT JOIN categories ON subcategory_id = category_id
It’s called a self-join. You incldue the table name twice in the query, but giving it two different aliases and then it’s just like a normal join: