views:

33

answers:

2

How to use ' LIMIT' in mysql database query based on fields . just consider a user has 10 phone number and i would like to get only 5 phone number for that user .

I would like to get only 5 phone numbers per user . not only 5 results from database ?

+1  A: 

Hmmm... this should be the same (regarding your last sentence):

SELECT phone_number FROM phone_numbers WHERE user_id = XX LIMIT 5

But if you're looking for a sub-select within another query, then you will have to use a JOIN and can't LIMIT this JOIN. So the way to go would be to first select the users and then - on a per-user-basis - select 5 phone numbers for every user.

Augenfeind
is there any other way to solve it ?
joe
Well, probably most SQL users wish there was a way to incorporate more than one subquery-result into one single main-query-result, but unfortunately there is no such possibility...
Augenfeind
+1  A: 

You can use "ROW_NUMBER() OVER PARTITION (..)" Mysql simulation for the situation Augenfeind described ( if you make a join and select no more than 5 phone numbers for each user ). See here to understand the logic: http://www.xaprb.com/blog/2005/09/27/simulating-the-sql-row%5Fnumber-function/

This would be something like:

SELECT * FROM 
users u JOIN
(
select l.user_id, l.phone, count(*) as num
from phones as l
left outer join phones as r
    on l.user_id = r.user_id
    and l.phone >= r.phone
group by l.user_id, l.phone
) p
ON u.user_id=p.user_id AND p.num<=5

Hope that helps.

StarWind Software
+1 Good answer :-)
joe