MySQL 在两个(或多个)给定值中选择最小值/最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19445828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL Select minimum/maximum among two (or more) given values
提问by Carlos
Is it possible to SELECT
the minimum or maximum among two or more values. I'd need something like this:
SELECT
两个或多个值中是否有可能取最小值或最大值。我需要这样的东西:
SELECT MAX_VALUE(A.date0, B.date0) AS date0, MIN_VALUE(A.date1, B.date1) AS date1
FROM A, B
WHERE B.x = A.x
Can I achieve this by only using MySQL?
我可以仅使用 MySQL 来实现这一点吗?
回答by Elon Than
You can use LEAST
and GREATEST
function to achieve it.
您可以使用LEAST
和GREATEST
函数来实现它。
SELECT
GREATEST(A.date0, B.date0) AS date0,
LEAST(A.date1, B.date1) AS date1
FROM A, B
WHERE B.x = A.x
Both are described here http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html
两者都在这里描述http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html
回答by RandomSeed
回答by Steve Childs
Just watch out if NULL is likely to be in a field value ...
只要注意 NULL 是否可能在字段值中......
SELECT LEAST(NULL,NOW());
and
和
SELECT GREATEST(NULL,NOW());
both return null, which may not be what you want (especially in the case of GREATEST)
两者都返回 null,这可能不是您想要的(尤其是在 GREATEST 的情况下)
回答by Mani
Try this:
尝试这个:
SELECT GREATEST(A.date0, B.date0) AS `date0`,LEAST(A.date0, B.date0) AS `date1`
FROM A
JOIN B
ON A.id = B.role;