简体   繁体   中英

Limit occurrence of records in MYSQL

I have created a view that combines two tables to show a list of email addresses and location details ie

Email Address One | Location 1
Email Address One | Location 2
Email Address One | Location 3
Email Address One | Location 4
Email Address Two | Location 1
Email Address Two | Location 2

This loops through a few hundred emails.

Unfortunately I need to limit each email address so only 5 records for each are selected - at present there are more than 70 records being returned for some records.

Is it possible to limit the number of each email address being returned to a maximum of 5 for example?

You need to add a rank to each email address in your return result, Eg

1 | Email Address One | Location 1
2 | Email Address One | Location 2
3 | Email Address One | Location 3
4 | Email Address One | Location 4
1 | Email Address Two | Location 1
2 | Email Address Two | Location 2

once you have that rank, you can add a where rank < 5. if you use a group clause to create the rank you will have to use a having clause eg having rank < 5.

Unfortunately I don't know your table's layout or your query to create the said results, therefore I cannot help you create the rank.

This has not been tested but might do the trick (assuming id is locations's unique identifier):

select 
    user.email AS email,
    locations.locationname AS locationname,
    count(A.id) AS rank
from 
    locations
    join user on (location.department = user.department)
    join locations A on A.id < locations.id
group by
    locations.id
having
    rank < 5
order by
    locations.id

How about using MySQL's LIMIT command? See http://dev.mysql.com/doc/refman/5.1/en/select.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM