mysql查询id最大 max,MySQL SELECT行的ID,其中几列的MAX条目最大

I have this table mytable:

+----+--------------------------------------+

| id | date1 | date2 | date3 |

+----+--------------------------------------+

| 1 | 2014-01-08 | NULL | NULL |

| 2 | 2014-05-09 | NULL | NULL |

| 3 | 2014-06-13 | NULL | NULL |

| 4 | NULL | 2014-03-24 | NULL |

| 2 | NULL | NULL | 2014-08-15 |

| 4 | 2014-01-01 | NULL | NULL |

| 1 | 2014-02-15 | NULL | NULL |

| 3 | NULL | 2014-12-06 | 2014-10-12 |

| 4 | 2014-08-06 | NULL | NULL |

| 2 | 2014-05-22 | NULL | NULL |

+----+--------------------------------------+

Now I try to have one SELECT with the following result:

id max_date1 max_date2 max_date3

---------------------------------------------

| 3 | 2014-08-06 | 2014-12-06 | 2014-10-12 |

That means the MAX of each date column and the ID from the row in which the GREATEST of the MAX results is.

The Query, that brought me nearly to the solution looks like this:

SELECT

id, max(date1), max(date2), max(date3), GREATEST(

IFNULL(max(date1), 0),

IFNULL(max(date2), 0),

IFNULL(max(date3), 0)) AS maxdate

FROM table1

But the id i get, is not the expected one. How can I find out which column has the maxdate so I can find out the appendant id?

解决方案

a way to do it would be to store your date in a user-defined-variable. then you can use it to pull out the id for the largest date

SET @A := (SELECT GREATEST(

IFNULL(max(date1), 0),

IFNULL(max(date2), 0),

IFNULL(max(date3), 0)

) FROM table1

);

-- here i JOIN a select that pulls out the correct id

SELECT t.joinid, max(`date1`), max(`date2`), max(`date3`)

FROM table1

JOIN

( SELECT id as joinid

FROM table1

WHERE @A IN -- WHERE my MAX date is in

(

SELECT date1 -- here the UNION is just putting all of the dates into one column to compare one date with

UNION ALL SELECT date2

UNION ALL SELECT date3

)

) t -- every table must have an alias

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值