Select 比 SQL table 差一个 table 的最高值
Select from SQL table by one table's highest values
我有一个 table 和 userID
s,一个 table 和 testID
s,以及一个 table 和 userID
s用 testID
秒。我怎么可能只用SQL,select每个userID
根据对应的最高testID
一次?
userIDTable: userID 1, userID 2, userID 3
mediatorTable: userID 1 testID 1, userID 2 testID 2, userID 1 testID 3, userID 2 testID 7, userID 3 testID 5
testIDTable: testID 1, testID 2, testID 3, testID 5, testID 7
SELECT userID 1 testID 3, userID 2 testID 7, userID 3 testID 5
每个用户只需要一行,最大的 testid
。
一个选项是 join
s,以及一个用于过滤预期测试的相关子查询。
select ... -- enumerate the columns that you want here
from mediator m
inner join users u on u.userid = m.userid
inner join tests t on t.test_id = m.testid
where m.testid = (
select max(m1.test_id)
from mediator m1
where m1.userid = m.userid
)
在MySQL 8.0中,您还可以使用window函数:
select ...
from (
select m.*,
row_number() over(partition by userid order by testid desc) rn
from mediator m
) m
inner join users u on u.userid = m.userid
inner join tests t on t.test_id = m.testid
where m.rn = 1
我有一个 table 和 userID
s,一个 table 和 testID
s,以及一个 table 和 userID
s用 testID
秒。我怎么可能只用SQL,select每个userID
根据对应的最高testID
一次?
userIDTable: userID 1, userID 2, userID 3
mediatorTable: userID 1 testID 1, userID 2 testID 2, userID 1 testID 3, userID 2 testID 7, userID 3 testID 5
testIDTable: testID 1, testID 2, testID 3, testID 5, testID 7
SELECT userID 1 testID 3, userID 2 testID 7, userID 3 testID 5
每个用户只需要一行,最大的 testid
。
一个选项是 join
s,以及一个用于过滤预期测试的相关子查询。
select ... -- enumerate the columns that you want here
from mediator m
inner join users u on u.userid = m.userid
inner join tests t on t.test_id = m.testid
where m.testid = (
select max(m1.test_id)
from mediator m1
where m1.userid = m.userid
)
在MySQL 8.0中,您还可以使用window函数:
select ...
from (
select m.*,
row_number() over(partition by userid order by testid desc) rn
from mediator m
) m
inner join users u on u.userid = m.userid
inner join tests t on t.test_id = m.testid
where m.rn = 1