开发者

MySQL: how do I do in inline function with ORDER BY?

So, I want to create a formula for ordering things by popularity, but I don't want to create a stored procedure or function. I'd like the function just to be in my query.

So, is there a way to do something like

SELECT cols
FROM tables
WHERE conditions
ORDER BY function(){ logic using cols } DESC LIMIT 10

开发者_如何学编程or something like that?


I don't want to create a stored procedure or function

You want to call a function but you don't want to define a function? Okay...

You can use expressions in the ORDER BY clause, including CASE which is pretty powerful:

SELECT cols
FROM tables
WHERE conditions
ORDER BY CASE WHEN col1 BETWEEN a AND b THEN 1 
              WHEN col1 BETWEEN c AND d THEN 2
              ...
         END
     DESC LIMIT 10

But it's often easier to do the calculation in your select-list and then order by that calculated column:

SELECT cols, POW(col1, col2) AS calc1
FROM tables
WHERE conditions
ORDER BY calc1 DESC LIMIT 10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜