Skip to content
Advertisement

SQL query to find largest id for each user_id

I am currently querying from 4 different tables,

users, memberships_users, membership_levels, phone_area_code

From the users table, I would like to select

The memberships_users table contains a user_id column as well as an id column. The user_id column is not unique, and there are many repeating user ids.

From the memberships_users table, I would like to select

from the row with the largest id for each user_id

and

name from the membership_levels table and

meta_value from the phone_area_code table

which should all relate the id in the users table

Advertisement

Answer

This is basically pseudo-code of one way of getting what you want.

First, create a derived table of each user_id and the max(id) from the membership table. This will yield all distinct user_id’s aligned with the associated max id from the membership. The next step is to join the two physical tables with the derived one to get the user and the associated membership record contain the max membership id.

NOTE : If your memberships_users table is on the large side then you will get better performance dropping the max_membership_id data into a temp table and adding appropriate indexes.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement