Query either field with highest number
I have 2 fields in a database table: "up" and "down" and they both have integer values.
up = 8
down = 4
To pull rows where up is more than down I use
$q开发者_运维知识库uery = "SELECT * FROM table WHERE up > down";
Suppose I want to pull the value of either field that has the highest number. How would I do this in a query?
SELECT IF(a > b, a, b) AS max_value
FROM (SELECT MAX(up) AS a,
MAX(down) AS b
FROM table) x
I found that the greatest()
function is ideal for my case http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest
SELECT GREATEST( up, down ) FROM table
精彩评论