MAX在mysql的两列上

时间:2012-06-26 08:44:07

标签: mysql sql query-optimization aggregate-functions

我想知道是否有更好的方法从列c1获得最大值,然后从列c2获得最大值,而不是

SELECT MAX(c1) , MAX(c2) FROM t GROUP BY c1 HAVING c1 = MAX(c1)

4 个答案:

答案 0 :(得分:4)

SELECT Max(t2.c1) as C1, 
       Max(t1.c2) as C2 
FROM   t t1 
       INNER JOIN (SELECT Max(c1) AS C1 
                   FROM   t) t2 
               ON t1.c1 = t2.c1 

答案 1 :(得分:1)

请阅读您对hkutluay的回复的评论,这可能是您想要的:

select MAX(colName)
from
(select col1 as colName
from tableName
union
select col2
from tableName) subqueryName

答案 2 :(得分:1)

我不太确定你是想要所有不同的c1还是仅仅是最大值。

如果你想要所有的c1:

SELECT c1, MAX(c2) FROM t GROUP BY c1;

如果您只想要最大值c1:

SELECT c1, c2 FROM t ORDER BY c1 DESC, c2 DESC LIMIT 1;

答案 3 :(得分:0)

我知道mysql没有CTE;但因为问题也标记为SQL,CTE是子查询的合理清洁解决方案,为了完整性,这里是一个CTE版本:

WITH zmax AS (
        SELECT MAX(v1) AS v1
        FROM ztable
        )
SELECT zt.v1
        , MAX(zt.v2) AS v2
FROM ztable zt
JOIN zmax mx ON zt.v1 = mx.v1
GROUP BY zt.v1
        ;