需要MySQL根据另一列的顺序按一列分组

时间:2013-09-16 19:00:05

标签: mysql

一些示例数据:

dashboard_items
diid      name          type
1         Tasks         large
2         Work Orders   large
3         Favorites     small
4         Sign-Ons      small
5         Sales Metrics chart

dashboard_item_controls
dicid    status      sortorder      diid
1        on          1              3
2        on          2              2
3        on          3              4
4        on          5              5
5        on          4              1

我的查询将为我提供以下结果:

diid      name          type
3         Favorites     small
4         Sign-Ons      small
2         Work Orders   large
1         Tasks         large
5         Sales Metrics chart

我在这里要做的是让查询识别具有最高排序顺序的项目,然后使用sortorder对其下面的所有相同类型项进行排序。然后,查询应该找到下一个类型并执行相同的操作,直到所有标记为“on”的项目都已排序。这将允许用户重新排列特定项目,但仅限于组(类型)本身。他们还可以重新排列整个组(例如,将图表移到小项目上方),但是他们不能,例如,放一个小项目后跟一个大项目,然后是另一个小项目。

我从以下查询开始作为基线:

SELECT dashboard_items.diid, dashboard_items.name, dashboard_items.type
FROM dashboard_item_controls
JOIN dashboard_items ON dashboard_item_controls.diid = dashboard_items.diid
WHERE status = 'on'
ORDER BY sortorder ASC

但当然,只需按sortorder排序并忽略类型字段。我尝试了GROUP BY和ORDER BY的变种,并没有任何运气。谁能指出我正确的方向?提前谢谢!

2 个答案:

答案 0 :(得分:3)

考虑到这一点:首先根据他们的类型创建组,然后按照排序顺序对组进行排序:

SELECT DISTINCT d.diid, d.name, d.type
FROM (
    SELECT d2.type, MIN(d1.sortorder) as srt
    FROM dashboard_item_controls d1
        JOIN dashboard_items d2 ON d1.diid = d2.diid
    WHERE d1.status = 'on'
    GROUP BY d2.type
    -- ORDER BY srt ASC -- As suggested, this is not required
    ) t JOIN dashboard_items d ON d.type = t.type
        JOIN dashboard_item_controls dd ON dd.diid = d.diid
WHERE dd.status = 'on'
ORDER BY t.srt ASC, dd.sortorder ASC

我没有花时间创作小提琴,也许还有一些小贴士。 希望它有所帮助。

答案 1 :(得分:0)

另一个版本,将两个表连接两次,一次获取sortorder值,一次获得该类型的最大值,然后相应地进行排序;

SELECT d.* 
FROM dashboard_items d
JOIN dashboard_item_controls dc ON d.diid=dc.diid
JOIN (
  SELECT MAX(sortorder) mx, type FROM dashboard_item_controls dic
  JOIN dashboard_items di ON di.diid=dic.diid
  GROUP BY type
) a
ON d.type = a.type 
WHERE dc.status = 'on' ORDER BY a.mx,dc.sortorder

An SQLfiddle to test with