我有这组规则来对 MySQL 和 sql-server 中的结果进行排序:
- 首先按
qty
排序- 从最高到最低 - 以上排序结果再次按
storage
排序,然后先放 2,比 值 >2,比 <2 - 以上排序结果再次按
price
排序- 从最低到 最高
我写了以下子句:
-
ORDER BY table.qty DESC
-
ORDER BY FIELD (table.storage, =2, >2, <2)
-
ORDER BY table.price ASC
对我来说,结合数据意味着:
qty,storage,price
0,0,0
1,1,10
1,2,22
1,3,10
2,3,10
1,2,9
我会得到:
qty,storage,price
2,3,10
1,2,9
1,2,22
1,1,10
1,3,10
0,0,0
我需要两件事的帮助:
1 - 第二个子句返回错误,我想这是因为操作符的错误使用:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '>2,<2)
2 - 如何将这些子句链接在一起
我真的不知道该怎么做,但让下面的伪查询来说明它:
SELECT
*
FROM
table
ORDER BY
table.qty DESC
AND
ORDER BY FIELD (
table.storage, =2, >2, <2
)
AND
ORDER BY
table.price ASC
最佳答案
对于 MSSQLServer 你可以使用
SELECT
*
FROM
table
ORDER BY
table.qty DESC,
CASE
WHEN table.storage = 2 THEN 1
WHEN table.storage > 2 THEN 2
WHEN table.storage < 2 THEN 3
END ASC,
table.price ASC
关于mysql - 按字段组合排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725681/