表中的SQL分组

时间:2013-06-09 06:26:24

标签: mysql

我正在尝试查看是否有办法让我对表进行分组和排序,而无需为同一目的开发另一个表。

我想要处理的主要标题是manufacturer_id, sort_order

在我的sort_order行中,我有1,2的几个值,然后其余的0有一种方法可以首先显示1,2然后0 1}}每manufacturer_id

结构:

CREATE TABLE IF NOT EXISTS `default_ps_products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `manufacturer_id` int(11) NOT NULL DEFAULT '0',
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `youtube` char(30) COLLATE utf8_unicode_ci NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '0',
  `on_special` tinyint(1) NOT NULL DEFAULT '0',
  `sort_order` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=90 ;

1 个答案:

答案 0 :(得分:1)

<强> UPDATE2

SELECT *
  FROM default_ps_products p
 ORDER BY manufacturer_id, 
          FIELD(COALESCE(sort_order, 0), 0),
          COALESCE(sort_order, 0)

示例输出:

| ID | MANUFACTURER_ID | SORT_ORDER |
-------------------------------------
|  2 |               1 |          1 |
|  4 |               1 |          1 |
|  3 |               1 |          2 |
|  1 |               1 |          0 |
|  5 |               1 |     (null) |
|  8 |               2 |          1 |
|  7 |               2 |          2 |
|  9 |               2 |          0 |
|  6 |               2 |          0 |
| 10 |               2 |     (null) |

这是 SQLFiddle 演示