tags:

views:

377

answers:

2

Hi,

I have a user table like this

user_id | community_id | registration_date
--------------------------------------------
1       |     1        | 2008-01-01
2       |     1        | 2008-05-01
3       |     2        | 2008-01-28
4       |     2        | 2008-07-22
5       |     3        | 2008-01-11

For each community, I would like to get the time that the 3rd user registered. I can easily do this for a single community using MySql's 'limit' SQL extension. For example, for community with ID=2

select registration_date
from user
order by registration_date
where community_id = 2
limit 2, 1

Alternatively, I can get the date that the first user registered for all communities via:

select community_id, min(registration_date) 
from user 
group by 1

But I can't figure out how to get the registration date of the 3rd user for all communities in a single SQL statement.

Cheers, Don

+3  A: 

With an inner select:

select 
  registration_date, community_id 
from 
  user outer 
where 
  user_id IN (
    select 
      user_id 
    from 
      user inner 
    where 
      inner.community_id = outer.community_id 
    order by 
      registration_date 
    limit 2,1
  )
order by registration_date

Selects the set of users where each user is the 3rd user in their community as returned by the limit clause in the inner select.

Adam Bellaire
This doesn't work because the inner select may return more than one value. The version of MySql I'm using doesn't permit a LIMIT to be used inside an inner select, so I can't simply replace the "=" with an "IN"
Don
Ah, yeah, old versions of MySQL can be a pain to work with. I'm not sure what you can do if you can't LIMIT the inner select.
Adam Bellaire
You probably have to break it out into multiple statements due to the limitations of your version.
Adam Bellaire
A: 

Is this what you mean?

SELECT registration_date
FROM user
ORDER BY registration_date
LIMIT n

Where n is the user you are concerned about.

chadgh
No, I want to get the Nth user registration date for each community
Don