简体   繁体   English

限制 MYSQL 中记录的出现

[英]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 地址和位置详细信息的列表,即

Email Address One | Email 地址一 | Location 1位置 1
Email Address One | Email 地址一 | Location 2位置 2
Email Address One | Email 地址一 | Location 3地点 3
Email Address One | Email 地址一 | Location 4位置 4
Email Address Two | Email 地址二 | Location 1位置 1
Email Address Two | Email 地址二 | Location 2位置 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.不幸的是,我需要限制每个 email 地址,因此每个地址只选择 5 条记录 - 目前,某些记录返回了 70 多条记录。

Is it possible to limit the number of each email address being returned to a maximum of 5 for example?例如,是否可以将返回的每个 email 地址的数量限制为最多 5 个?

You need to add a rank to each email address in your return result, Eg您需要在返回结果中为每个 email 地址添加一个排名,例如

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.获得该排名后,您可以添加 where rank < 5。如果您使用 group 子句创建排名,则必须使用 having 子句,例如 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):这尚未经过测试,但可能会起作用(假设 id 是位置的唯一标识符):

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?使用 MySQL 的 LIMIT 命令怎么样? See http://dev.mysql.com/doc/refman/5.1/en/select.html .请参阅http://dev.mysql.com/doc/refman/5.1/en/select.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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