我需要你的帮助进行内部连接和最大值。我已经研究了其他问题,但我无法解决。。。
我有三张桌子:
- 成员(member_id,name)
- location(location_id、name、order)
- member_location(id,member_id,location_id)
我只需要根据member_location.memberId从具有最高顺序组的member_location中选择记录。
示例:
Member
1, Jack Sparrow
Location
1, Mexico, 2
2, Punta Cana, 3
3, Cuba, 1
member_location
1, 1, 3
1, 1, 2
1, 1, 1
在member_location上,我有同一成员的3条记录,在我的查询中,我需要获得member_location的第二行(1,1,2),因为位置2的顺序最大。
我尝试:
select ml.memberId, ml.locationId, max(l.order)
from member_location ml inner join
location l
on ml.locationId=l.id
group by ml.memberId;
结果:1,1,3-订单还可以,但位置ID号
我也尝试过:
select ml.locationId, ml.memberId
from member_location ml inner join
(select id, max(order) from location) l
on ml.locationId = l.id
group by ml.memberId;
在响应中,我收到了第一个位置的记录。
如果只想返回一行,可以使用order by
和limit
:
select ml.memberId, ml.locationId
from member_location ml inner join
location l
on ml.locationId=l.id
order by l.order desc
limit 1;
我想这可能就是你想要的:
select ml.memberId, ml.locationid
from member_location ml
inner join location l on ml.locationId = l.id
where l.order = (
select max(order) max_order
from location
join member_location on location.id = member_location.locationid
where member_location.memberid = ml.memberid
)
这将为任何用户获得最高顺序的位置;不限于一个。相关子查询确保最大值(order)仅应用于与用户相关的位置集(如果没有相关,最大值(order)可能是特定用户member_locations不包括的位置)。
如果只需要特定用户的数据,可以在查询末尾添加where ml.memberId = ?
。