我有一个数据库表,其中包含不同的类别,其中包含不同的产品,每个类别都具有某些优先级。假设cat-1有5个乘积,cat-2包含3个乘积,cat-3包含3个乘积,cat-4包含2个乘积。

在展示产品时,顺序应如下。

如果类别具有相同的优先级(假设cat-1,cat-2优先级= 1,cat-3优先级= 2,cat-4优先级= NULL),则产品将显示如下。

c1p1,c2p1,c1p2,c2p2,c1p3,c2p3,c1p4,c1p5,c3p1,c3p2,c3p3,c4p1,c4p2。

如果类别具有相同的优先级(假设cat-1,cat-2优先级= 1,cat-3和cat-4优先级= 2),则产品将显示如下。

c1p1,c2p1,c1p2,c2p2,c1p3,c2p3,c1p4,c1p5,c3p1,c4p1,c3p2,c4p2,c3p3。

如果类别具有不同的优先级(假设类别1优先级= 2,类别2优先级= 1,类别3优先级= 3,类别4优先级=空),则产品将显示如下。

c2p1,c2p2,c2p3,c1p1,c1p2,c1p3,c1p4,c1p5,c3p1,c3p2,c3p3,c4p1,c4p2。

这里c =类别,p =乘积。

在MySQL中可以进行这种排序吗?请帮忙。

这是数据库表的结构和样本数据-

   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');

最佳答案

您可以创建具有优先级的表:

create table priorities (
  category varchar(255),
  priority int null);


然后您可以通过以下方式选择产品:

select
  products.*
from
  products inner join priorities
  on products.category = priorities.category
order by
  priorities.priority is null, -- this to put null values at the end
  priorities.priority,
  products.id                  -- or some other field


编辑:这可能是您正在寻找:

select
  products.name
from
  products inner join categories
  on products.category_id = categories.id
order by
  categories.priority is null,
  categories.priority,
  substr(products.name,3),
  categories.name

关于mysql - MySQL自定义排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13910248/

10-11 22:43
查看更多