MySql按函数的结果排序

时间:2018-02-21 14:12:46

标签: mysql

假设我有一个SQL表,我想根据计算结果对其进行排序。

 ID   user_id   field_id  value
 10      1         11      name 1
 11      1         12      13.22333    // A
 12      1         13      45.3322     // B
 13      2         11      name 2
 14      2         12      120.99      // A
 15      2         13      99.343      // B

我有像这样的SQL函数

   calc(float A,float B) {
     return A*B;
   }

我必须根据calc中的返回值对用户进行排序:

  A=value when field_id=12
  B=value when field_id=13

  select * from table order by calc(A,B)

有人知道正确的MYSQL语法吗?

输出是user_id的列表,使用calc函数

进行排序

2 个答案:

答案 0 :(得分:0)

自我加入:

 SELECT A.user_id, calc(A.value, B.value)
 FROM table as A
 JOIN table as B
   ON A.user_id = B.user_id
 WHERE A.field_id  = 12
   AND B.field_id  = 13
 ORDER BY calc(A.value, B.value)

使用一个电话:

 SELECT *
 FROM (
     SELECT A.user_id, calc(A.value, B.value) as Total
     FROM table as A
     JOIN table as B
       ON A.user_id = B.user_id
     WHERE A.field_id  = 12
       AND B.field_id  = 13
) as T
ORDER BY Total

答案 1 :(得分:0)

您也可以在不使用function的情况下实现相同目标。

解决方案1 ​​

 SELECT A.user_id, A.value * B.value as calculatedVal
 FROM table as A
 JOIN table as B
   ON A.user_id = B.user_id
 WHERE A.field_id  = 12
   AND B.field_id  = 13
 ORDER BY (A.value * B.value)

解决方案2

 SELECT A.user_id, A.value * B.value as calculatedVal
 FROM table as A
 JOIN table as B
   ON A.user_id = B.user_id
 WHERE A.field_id  = 12
   AND B.field_id  = 13
 ORDER BY calculatedVal