mysql inner join max

亡梦爱人 提交于 2019-12-13 15:14:50

问题


I need your help with a inner join and max. I already researched other questions but I could not solve...

I have three tables:

  • member (member_id, name)
  • location (location_id, name, order)
  • member_location (id, member_id, location_id)

I need select just the record from member_location with the highest order group by member_location.memberId.

Example:

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

On member_location I have 3 records for the same member, with my query I need get the second row of member_location (1, 1, 2) because the order of location 2 is the greatest .

I try:

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;

result: 1,1,3 -The order it's ok but the locationId no.

I also try:

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;

On the response I receive the record with the first location.


回答1:


I think maybe this is what you want:

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
)

This would get the location with the highest order for any user; not limited to one. The correlated subquery makes sure that the max(order) is applied only to the set of locations relevant for the user (without the correlation the max(order) could be a location that the specific users member_locations doesn't include).

If you only want data for a specific user you can add a where ml.memberId = ? at the end of the query.




回答2:


If you only want one row back, you can use order by and 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;


来源:https://stackoverflow.com/questions/29336064/mysql-inner-join-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!