Note that there are some explanatory texts on larger screens.

plurals
  1. POMysql custom sort
    text
    copied!<p>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.</p> <p>While displaying the products, the order should be as follows.</p> <p>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.</p> <p>c1p1, c2p1, c1p2, c2p2, c1p3, c2p3, c1p4, c1p5, c3p1, c3p2, c3p3, c4p1, c4p2.</p> <p>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.</p> <p>c1p1, c2p1, c1p2, c2p2, c1p3, c2p3, c1p4, c1p5, c3p1, c4p1, c3p2, c4p2, c3p3.</p> <p>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.</p> <p>c2p1, c2p2, c2p3, c1p1, c1p2, c1p3, c1p4, c1p5, c3p1, c3p2, c3p3, c4p1, c4p2.</p> <p>Here c = category and p = product.</p> <p>Can this type of sorting is possible in Mysql. Please help.</p> <p>Here is the structure and sample data of the database tables-</p> <pre><code> 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'); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload