Reputation: 2344
I am trying to get results from mysql by not letting a specific field gets repeated more than 5 times.
For example, lets say that I have a table like this :
-------------
Name City
person1 Nashville
person2 Nashville
person3 Nashville
person4 Nashville
person5 Nashville
person6 Nashville
person7 New York
-------------
What I want it to return is this :
-------------
Name City
person1 Nashville
person2 Nashville
person3 Nashville
person4 Nashville
person5 Nashville
person7 New York
-------------
where the city field cannot be repeated more than five times! if it was repeated more than fix times, only return the first five results.
This question could be impossible (that is what I am guessing) but if there is a solution or anyway to work around what I am trying to achieve, please tell me! I can use PHP.
Upvotes: 2
Views: 109
Reputation: 11714
Are you allowed to perform more than one MySql command? If so, you can try doing two separate calls --
SELECT name, city FROM table WHERE city = 'Nashville' ORDER BY name LIMIT 5;
SELECT name, city FROM table WHERE city <> 'Nashville' ORDER BY name;
Someone may need to check on this but the general idea stands. The only problem with this is your end result would not have the table ordered by name. Rather, it'd have the people with the city has 'Nashville' first, and then everyone else.
Upvotes: -1
Reputation: 247650
How about something like this which uses variables to check the current row to the previous row, if they are the same then the row number will increase if they are not the row number will reset:
select name, city
from
(
select name,
city,
@row:=(case when @prev=city then @row else 0 end) + 1 as rownum,
@prev:=city pcity
from yourtable
order by city, name
) src
where rownum <= 5
The result is:
| NAME | CITY |
-----------------------
| person1 | Nashville |
| person2 | Nashville |
| person3 | Nashville |
| person4 | Nashville |
| person5 | Nashville |
| person7 | New York |
Upvotes: 7
Reputation: 33935
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.name <= x.name
AND y.city = x.city
GROUP
BY x.city
, x.name
HAVING COUNT(*) <= 5;
Upvotes: 1