I have a database table containing different category which contains different products and each category having some priority. Suppose cat-1 have five products, cat-2 contains 3 products, cat-3 contains 3 products and cat-4 contains 2 products.
While displaying the products, the order should be as follows.
If categories have same priority (suppose cat-1, cat-2 priority = 1, cat-3 priority = 2, cat-4 priority = NULL), then products will display as follow.
c1p1, c2p1, c1p2, c2p2, c1p3, c2p3, c1p4, c1p5, c3p1, c3p2, c3p3, c4p1, c4p2.
If categories have same priority (suppose cat-1, cat-2 priority = 1, cat-3 and cat-4 priority = 2), then products will display as follow.
c1p1, c2p1, c1p2, c2p2, c1p3, c2p3, c1p4, c1p5, c3p1, c4p1, c3p2, c4p2, c3p3.
If categories have different priority (suppose cat-1 priority = 2, cat-2 priority = 1, cat-3 priority = 3 and cat-4 priority = Null), then products will display as follow.
c2p1, c2p2, c2p3, c1p1, c1p2, c1p3, c1p4, c1p5, c3p1, c3p2, c3p3, c4p1, c4p2.
Here c = category and p = product.
Can this type of sorting is possible in Mysql. Please help.
Here is the structure and sample data of the database tables-
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`priority` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
INSERT INTO `categories` (`id`, `name`, `priority`) VALUES
(1, 'c1', 1),
(2, 'c2', 1),
(3, 'c3', 2),
(4, 'c4', NULL);
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ;
INSERT INTO `products` (`id`, `category_id`, `name`) VALUES
(1, 1, 'c1p1'),
(2, 1, 'c1p2'),
(3, 1, 'c1p3'),
(4, 1, 'c1p4'),
(5, 1, 'c1p5'),
(6, 2, 'c2p1'),
(7, 2, 'c2p2'),
(8, 2, 'c2p3'),
(9, 3, 'c3p1'),
(10, 3, 'c3p2'),
(11, 3, 'c3p3'),
(12, 4, 'c4p1'),
(13, 4, 'c4p2');
Finally i got a better solution. I added an extra field in the products table. The motive is to give a serial number to each category products. My final products table structure look as follows.
And the query looks like-