Mysql 如何获取最大值为一列的行

Mysql 如何获取最大值为一列的行,mysql,sql,Mysql,Sql,我想从如下表中获得maxtestid(其中studyid等于6)的行 seq | studyid | buildnumber | testid | 1 | 6 | 1904 | 1 | 2 | 6 | 1904 | 1 | 3 | 6 | 1904 | 1 | 4 | 6 | 1029 | 3 | 5

我想从如下表中获得max
testid
(其中
studyid
等于6)的行

 seq | studyid  | buildnumber |  testid |
 1   |    6     |   1904      |    1    |
 2   |    6     |   1904      |    1    | 
 3   |    6     |   1904      |    1    | 
 4   |    6     |   1029      |    3    | 
 5   |    6     |   1029      |    3    | 
 6   |    6     |   1104      |    5    | 
 7   |    6     |   1104      |    5    | 
 8   |    6     |   3049      |    4    | 
 9   |    6     |   3049      |    4    | 
10   |    7     |   4029      |    11   | 
11   |    8     |   5049      |    21   | 
12   |    9     |   6049      |    14   | 
13   |   10     |   7049      |    54   | 
14   |   11     |   8049      |    13   | 
预期结果将是

6   |    6     |   1104    |    5    | 
我想问的是

select max(buildnumber) buildnumber, max(testid) testid, studyid 
from testdata 
where studyid = 6

有人能帮我吗?

如果我理解您想要的逻辑(对于
studyid=6
,最大的
testid
,然后使用
order by
limit

select t.*
from testdata t
where studyid = 6
order by testid desc
limit 1;

注意,这可能返回第6行或第7行。问题的措辞是“获取具有最大testid的行…”,这意味着只有一行。但是,示例数据有两行这样的行,没有解释如何选择其中一行。

使用order by先获取目标行,然后使用llomit:

select *
from testdata
where studyid = 6
order by testid desc, seq
limit 1

虽然没有说明,但您的示例数据表明,msx testid的连接应该使用最低的seq来断开,因此在order by子句中有seq。

@YellowBird…将是id为6或7的行。您能解释一下您的评论吗?@YellowBird…当然是。这是
testid
的最大值。如果我没有看到这一点,我会的ldn尚未回答。请注意,答案是从对问题的理解开始的(我欢迎OP对此进行评论)。我不确定,但此答案可能无法保证选择seq=6的行(作为所需结果的一部分给出),因为有两行具有相同的
testid
。您的“预期结果"是max?1104不是最大的buildnumber。@PatrickQ…testid是max。@GordonLinoff啊,我在查询中没有注意到。编辑得好,这会让它更清楚。@Kyungmo为什么它要返回
6 1104 5
而不是
7 6 1104 5
行?@PatrickQ好吧,它会让它更清楚一点。还有空间吗r尽管有改进!;-)