165

Is it possible to SELECT the minimum or maximum among two or more values. I'd need something like this:

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?

Carlos
  • 4,949
  • 2
  • 20
  • 37
  • 1
    possible duplicate of [How to get the max of two values in MySQL?](http://stackoverflow.com/questions/1565688/how-to-get-the-max-of-two-values-in-mysql) – RandomSeed Oct 18 '13 at 09:18

4 Answers4

309

You can use LEAST and GREATEST function to achieve it.

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

Elon Than
  • 9,603
  • 4
  • 27
  • 37
30

I suppose you are looking for:

GREATEST()

and

LEAST()

RandomSeed
  • 29,301
  • 6
  • 52
  • 87
20

Just watch out if NULL is likely to be in a field value ...

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)

Steve Childs
  • 1,832
  • 2
  • 20
  • 26
3

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;
Mani
  • 888
  • 6
  • 19