简体   繁体   English

MySQL:按两列函数排序

[英]MySQL: Order by a function of two columns

I have two integer fields A and B in table T . 我在表T中有两个整数字段A和B.

I want to do something like " SELECT * FROM T ORDER BY f(A,B) DESC " 我想做类似“ SELECT * FROM T ORDER BY f(A,B) DESC ”之类的事情

where f(A,B) is a linear combination of A and B ... ie f(A,B) = mA + nB , where m and n are numbers. 其中f(A,B)是A和B的线性组合......即f(A,B) = mA + nB ,其中m和n是数字。

What is the right syntax? 什么是正确的语法?

You have two options (at least): 你有两个选择(至少):

SELECT (n * A + m * B) AS C, *
  FROM T
 ORDER BY C DESC; -- or ORDER BY 1 DESC

Or: 要么:

SELECT *
  FROM T
 ORDER BY (n * A + m * B) DESC;

One or the other - possibly both - should work for you in MySQL. 一个或另一个 - 可能两者 - 应该在MySQL中为你工作。 The first should work even if the second does not. 第一个应该工作,即使第二个没有。

Try to keep it simple, use the following: 尽量保持简单,使用以下内容:

SELECT * FROM T ORDER BY (m * A + n * B) DESC

where m and n are on your responsibility. 其中m和n是你的责任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM