Mysql: Problem using GREATEST with IFNULL and join

MySQLselect

I have a query selecting the greatest value of 2 timestamps.

To achieve it I'm calling:

SELECT GREATEST( IFNULL( tableb.create_time, 0 ) , IFNULL( tablea.create_time, 0 ) )

I'm using IFNULL because the create_time value can be null.
The problem is that the result is something like '2014-0' instead of '2014-08-14 17:04:39'

Here's a fiddle to illustrate my problem

The result is OK when:

  • I'm not using IFNULL
  • I'm using IFNULL but I have no join in the query (so the GREATEST is performed on 2 timestamps in the same table)

So for me the problem comes really from the use of GREATEST and IFNULL in a join query.

Best Answer

SELECT
    GREATEST
    (
        IFNULL(tableb.create_time,FROM_UNIXTIME(18000)),
        IFNULL(tablea.create_time,FROM_UNIXTIME(18000))
    );

It just so happens that FROM_UNIXTIME(18000) is '1970-01-01 00:00:00'