SQL按其他表字段的顺序排列元素,但按一定顺序排列

时间:2019-10-21 09:53:43

标签: mysql wordpress

我有2张桌子:

  • object
    • ID
    • title
  • category
    • ID
    • title
    • object_id

我想设置一个查询,以按自定义顺序按类别获取对象顺序,例如,第一个类别ID为214,第二个219等的对象,等等。

我正在执行以下查询:

SELECT SQL_CALC_FOUND_ROWS
  object.* 
FROM object
INNER JOIN category
  ON category.object_id = object.ID 
WHERE 1 = 1
GROUP BY object.ID 
ORDER BY
  CASE category.ID 
    WHEN 214 THEN 1 
    WHEN 219 THEN 2 
    WHEN 220 THEN 3 
    WHEN 216 THEN 4 
    WHEN 222 THEN 5 
    WHEN 223 THEN 6 
    WHEN 225 THEN 7 
    WHEN 218 THEN 8 
    WHEN 326 THEN 9 
    WHEN 224 THEN 10 
    WHEN 221 THEN 11 
    WHEN 215 THEN 12 
    WHEN 229 THEN 13 
    WHEN 228 THEN 14 
    WHEN 217 THEN 15 
    WHEN 188 THEN 16 
    WHEN 230 THEN 17 
    WHEN 327 THEN 18 
  END ASC
  , object.title ASC
LIMIT 0, 23

但是它不起作用,它返回按object.title排序但不按category.ID排序的对象。

2 个答案:

答案 0 :(得分:0)

将订单更改为

ORDER BY FIELD(category.ID,214,219,220,216,222,223,225,218,326,224,221,215,229,
  228,217,188,230,327),object.title ASC

实现目标

答案 1 :(得分:-1)

您可以在类别表中添加名称为order_number的字段,并在那里设置顺序。然后只需按order_number进行排序。这还将减少您的查询并对其进行优化。

SELECT SQL_CALC_FOUND_ROWS
  object.*
FROM object
INNER JOIN category
  ON category.object_id = object.ID
WHERE 1 = 1
GROUP BY object.ID
ORDER BY category.order_number
  , object.title ASC
LIMIT 0, 23