如何通过排除组数组来获取MySQL表的前N条记录


How can I get the top N records of a MySQL table by excluding an array of groups?

下面是一个表格示例:

Table: websites
Domain            | Category | Popularity
google.com        | 0        | 13,430
yahoo.com         | 0        | 1,094
facebook.com      | 1        | 23,943
youtube.com       | 2        | 17,320
imdb.com          | 3        | 6,094
stackoverflow.com | 4        | 2,930
ebay.com          | 5        | 5,748
yandex.com        | 5        | 3,748

我想通过排除按受欢迎程度排序的类别CE=[C1,C2,C3…Cn]来返回前N个结果。

例如:

按受欢迎程度排序,排除搜索引擎CE=[0]后的前三名结果为:

Domain            | Category | Popularity
facebook.com      | 1        | 23,943
youtube.com       | 2        | 17,320
imdb.com          | 3        | 6,094

排除除搜索引擎CE=[1,2,3,4,5]以外的所有类别的前三名结果按受欢迎程度排序为:

Domain            | Category | Popularity
google.com        | 0        | 13,430
yahoo.com         | 0        | 1,094

让我们处理最后一个查询。

我希望它看起来像这样:

SELECT domain, category, popularity FROM (SELECT domain, category, popularity FROM websites WHERE category != [1, 2, 3, 4, 5] ORDER BY popularity) LIMIT 0, 3
  1. 如何将排除的类别数组作为WHERE语句传递
  2. 如何按受欢迎程度的升序/降序排序
  3. 我是在选择类别类型正确的产品之前还是之后订购(性能方面(

我不在乎回应是否受欢迎。这是我可以重做客户端的东西。

我知道这是核心级别的东西,但有什么方法可以加快速度吗?这毕竟是整张桌子的扫描!

您可以使用LIMIT子句来完成此操作,所要做的就是确保WHERE子句筛选出您不想要的类别。试试这个:

SELECT *
FROM myTable
WHERE category NOT IN(category, list)
ORDER BY popularity DESC
LIMIT 3;

传入列表的方法是找到一种方法来构建一个以逗号分隔的要筛选的类别列表。有关IN运算符的更多信息,请参阅此链接。

下面是一个SQLFiddle示例,它显示了您的两个示例案例。

select *
from websites
where Category in (1, 2, 3, 4, 5)
order by Popularity desc
limit 0,3;

将为您提供3个最受欢迎的域名,它们属于类别1、2、3、4或5

select *
from websites
where Category not in (1, 2, 3, 4, 5)
order by Popularity desc
limit 0,3;

将为您提供3个不在类别1、2、3、4或5 中的最受欢迎的域