具有特定条件的MySQLl键值存储排序

时间:2019-05-13 18:44:09

标签: mysql sql-order-by key-value-store

我具有以下结构:

+----------+--------+---------------------+
| id| gr_id| name   | value               |
+----------+--------+---------------------+
| 1  |  11 | name   | Burro               |
| 2  |  11 | submit | 2019/05/10          |
| 3  |  11 | date   | 2019/05/17          |   
| 4  |  12 | name   | Ajax                |
| 5  |  12 | submit | 2019/05/10          |
| 6  |  12 | date   | 2019/05/18          | 
+----------+--------+---------------------+

我必须按日期(如果名称是日期)从最高日期到最低日期进行排序,它还必须保留组(gr_id),而不能混淆元素。

所需的结果如下:

+----------+--------+---------------------+
| id| gr_id| name   | value               |
+----------+--------+---------------------+
| 4  |  12 | name   | Ajax                |
| 5  |  12 | submit | 2019/05/10          |
| 6  |  12 | date   | 2019/05/18          |   
| 1  |  11 | name   | Burro               |
| 2  |  11 | submit | 2019/05/10          |
| 3  |  11 | date   | 2019/05/17          | 
+----------+--------+---------------------+

我该如何实现?

1 个答案:

答案 0 :(得分:1)

您必须将组订购条件与组中的所有元素相关联。您可以通过子查询或联接来实现。

子查询版本:

SELECT t.*
FROM (SELECT gr_id, value as `date` FROM t WHERE `name` = 'date') AS grpOrder
INNER JOIN t ON grpOrder.gr_id = t.gr_id
ORDER BY grpOrder.`date`
, CASE `name` 
   WHEN 'name' THEN 1 
   WHEN 'submit' THEN 2
   WHEN 'date' THEN 3
   ELSE 4
 END

加入版本:

SELECT t1.*
FROM t AS t1
INNER JOIN AS t2 ON t1.gr_id = t2.gr_id AND t2.`name` = 'date'
ORDER BY t2.value
, CASE t1.`name` 
   WHEN 'name' THEN 1 
   WHEN 'submit' THEN 2
   WHEN 'date' THEN 3
   ELSE 4
 END