获取具有Min()值的记录的ID

时间:2019-01-29 16:59:35

标签: mysql

我有一个复杂的mysql查询,其中Select字段之一是Min(value)。由于所有“值”都是唯一的,是否还有一种方法来获取找到的最小值的行ID?

换句话说,如果我们将查询简化为这个问题,则是这样的:

SELECT t1.name, MIN(t2.value) AS minval
FROM table1 t1 
LEFT JOIN table2 t2
    ON t2.id_user = t1.id
GROUP BY id_user

我现在如何知道为特定用户的最低t2.value选择了哪个t2.id?谢谢!

2 个答案:

答案 0 :(得分:0)

使用ROW_NUMBER()查找每个value中的第一个id_user

您可以将*替换为所需的字段

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY t2.id_user ORDER BY t2.value) as rnk
    FROM table1 t1 
    LEFT JOIN table2 t2
        ON t2.id_user = t1.id
) as X
WHERE X.rnk = 1

答案 1 :(得分:0)

也许这很简单,不知道您的陈述有多复杂:

   SELECT name,value,id
    FROM(
    SELECT t1.name,t2.value,t2.id
    FROM table1 t1 
    LEFT JOIN table2 t2
        ON t2.id_user = t1.id
    GROUP BY t2.id,id_user
    ORDER BY t1.name,t2.id asc) as test
    GROUP BY name;