我有一个名为$ var的PHP变量。我想根据$ var对结果进行排序。这个有效:
function myFunc(id: string) {
id = "(";
};
// Note that this function does nothing, but it's not the issue here
let id: string = ")";
if (id !== '(')
throw "Expected '(' in prototype";
// id is narrowed to "("
myFunc(id);
// now id and ')' does not have same type, hence the error
if (id !== ')')
throw "Expected ')' in prototype";
但是当$ var为3时,我需要使用$sql = "
SELECT
myText1,
myText2,
someNumber
FROM myTable
ORDER BY
CASE
WHEN $var = 1 THEN myText1
WHEN $var = 2 THEN myText2
WHEN $var = 3 THEN someNumber
END";
按someNumber
排序。所以我尝试了这个:
DESC
这会引发语法错误。我怎样才能做到这一点?
答案 0 :(得分:2)
将其拆分为三个case
表达式:
ORDER BY (CASE WHEN $var = 1 THEN myText1 END) ASC,
(CASE WHEN $var = 2 THEN myText2 END) ASC,
(CASE WHEN $var = 3 THEN someNumber END) DESC
ASC
当然是可选的 - 只需与DESC
签订合同。
更重要的是,这会删除自动转换。 CASE
表达式只返回一种类型。混合使用不同类型时,会发生某种转换。该转换可能会影响值的排序。这解决了这个问题。
答案 1 :(得分:0)
使用数学:
ORDER BY
CASE
WHEN $var = 1 THEN myText1
WHEN $var = 2 THEN myText2
WHEN $var = 3 THEN 1000000 - someNumber
END
答案 2 :(得分:0)
CASE只能返回一个表达式,因此您将遇到几种情况:
CASE WHEN $var = 1 THEN myText1 END,
CASE WHEN $var = 2 THEN myText2 END,
CASE WHEN $var = 3 THEN someNumber END DESC
OR,优化
CASE
WHEN $var = 1 THEN myText1,
WHEN $var = 2 THEN myText2
END,
CASE WHEN $var = 3 THEN someNumber END DESC