【问题标题】:mysql inner join maxmysql内部连接最大值
【发布时间】:2015-03-29 23:09:59
【问题描述】:

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

我有三张桌子:

  • 成员(member_id,姓名)
  • 位置(location_id、名称、订单)
  • member_location (id, member_id, location_id)

我只需要从 member_location 中选择按 member_location.memberId 排序最高的记录。

例子:

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;

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

【问题讨论】:

  • member_loction表中的id列是做什么的,为什么总是1
  • 对不起,我的错误。列 id 是主键,我输入了错误的数字。但我认为这种情况无关紧要
  • 我怀疑是否存在与它相关的案例;-)

标签: mysql max inner-join


【解决方案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;

【讨论】:

  • 按预期工作!许多 tks ;)
【解决方案2】:

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

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(order) 仅应用于与用户相关的位置集(没有相关性, max(order) 可能是特定用户 member_locations 不包括的位置)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多