mysql内连接最大值

时间:2015-03-29 23:10:00

标签: mysql max inner-join

我需要你的内部联接和最大帮助。我已经研究过其他问题,但我无法解决......

我有三张桌子:

  • member(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-订单没问题但是locationId没有。

我也试试:

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;

在回复中,我收到第一个位置的记录。

2 个答案:

答案 0 :(得分:1)

如果您只想要退回一行,则可以使用order bylimit

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;

答案 1 :(得分:0)

我想也许这就是你想要的:

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
)

这将获得任何用户的最高订单的位置;不限于一个。相关子查询确保max(顺序)仅应用于与用户相关的位置集(没有相关性,max(order)可以是特定用户member_locations不包括的位置)。 / p>

如果您只想要特定用户的数据,可以在查询结尾添加where ml.memberId = ?