MySQL ORDER BY CASE无效

时间:2016-09-23 21:05:14

标签: mysql

我正在尝试按照匹配的部分,细分和键映射的顺序来整理我的结果。现在我得到错误,但我认为我正在走上正确的道路来完成这个。我无法弄清楚如何正确设置我的案例按此顺序进行。

编辑:

我已经更新了有效的查询,但它仍然没有按正确的顺序排序。

SELECT 
    list.WorkOrder,
    list.Address,
    locateparsed.CrossStreet,
    list.Section,
    list.Subdivision,
    locateparsed.KeyMap,
    locateparsed.City,
    list.Score
FROM list 
LEFT JOIN locateparsed ON locateparsed.WorkOrder = list.WorkOrder
    WHERE locateparsed.City = "PEARLAND"
    AND list.Completed = 0
    AND list.Reference = 0
    AND locateparsed.Ticket IS NOT NULL
GROUP BY list.WorkOrder
ORDER BY CASE
    WHEN list.Section = 'Sec. 1' THEN 1
    WHEN list.Subdivision = 'Shadow Ridge' THEN 2
    WHEN locateparsed.KeyMap = '612P' THEN 3 
END

输出示例:

WO | Address | CrossStreet | Section | Subdivision | KeyMap | City
1 | 123 test | other | Sec. 1 | Shadow Ridge | 612P | Pearland
2 | 111 test | other | Sec. 1 | Shadow Ridge | 612P | Pearland
3 | 333 other | bleach | Sec. 2 | Shadow Ridge | 612P | Pearland
4 | 334 other | bleach | Sec. 2 | Shadow Ridge | 612P | Pearland
5 | 848 other | bleach | Sec. 2 | Shadow Ridge | 612P | Pearland
6 | 733 blah | random | Sec. 5 | Bright Ridge | 612P | Pearland
7 | 722 hmm | blah | Sec. 5 | Bright Ridge | 612P | Pearland
8 | 723 hmm | blah | Sec. 5 | Bright Ridge | 612P | Pearland
9 | 111 asdf | fdas | Sec. 30 | Other Ridge | 650P | Pearland
10 | 123 asdf | fdas | Sec. 30 | Other Ridge | 650P | Pearland

1 个答案:

答案 0 :(得分:1)

你的语法错了。它应该是:

ORDER BY CASE
    WHEN list.Section = 'Sec. 1' THEN 1
    WHEN list.Subdivision = 'Shadow Ridge' THEN 2
    WHEN locateparsed.KeyMap = '612P' THEN 3
    ELSE 4 -- anything that doesn't match above conditions comes last
END

整个END表达式只有一个CASE,而不是每个WHEN之后,而WHEN子句之间没有逗号。