如何通过排除一组数组来获取 MySQL table 的前 N 条记录?
How can I get the top N records of a MySQL table by excluding an array of groups?
这是一个 table 示例:
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
whosebug.com | 4 | 2,930
ebay.com | 5 | 5,748
yandex.com | 5 | 3,748
我想 return 通过排除类别 CE = [C1, C2, C3 ... Cn] 按受欢迎程度排序的前 N 个结果。
例如:
排除搜索引擎CE=[0]的TOP 3结果按热度排序为:
Domain | Category | Popularity
facebook.com | 1 | 23,943
youtube.com | 2 | 17,320
imdb.com | 3 | 6,094
排除除搜索引擎CE = [1, 2, 3, 4, 5]以外的所有类别的TOP 3结果按流行度排序为:
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
- 如何将排除的类别数组作为 WHERE 语句传递?
- 如何按人气升序/降序排序?
- 我是在 select 具有正确类别类型(性能方面)的那些之前还是之后订购它?
我不在乎响应是否按受欢迎程度排序。这是我可以 重做 客户端的东西。
我知道这是核心级别的东西,但有什么办法可以加快它的速度吗?毕竟是全table扫描!
select *
from websites
where Category in (1, 2, 3, 4, 5)
order by Popularity desc
limit 0,3;
将为您提供类别 1、2、3、4 或 5 中的 3 个最受欢迎的域
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 的最受欢迎的域
您可以使用 LIMIT
子句来做到这一点,您所要做的就是确保您的 WHERE
子句过滤掉您不想要的类别。试试这个:
SELECT *
FROM myTable
WHERE category NOT IN(category, list)
ORDER BY popularity DESC
LIMIT 3;
传递列表的方法是找到一种方法来构建要过滤掉的类别的逗号分隔列表。有关 IN
运算符的详细信息,请参阅 this link。
这是一个 SQL Fiddle 示例,其中显示了您的两个示例案例。
这是一个 table 示例:
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
whosebug.com | 4 | 2,930
ebay.com | 5 | 5,748
yandex.com | 5 | 3,748
我想 return 通过排除类别 CE = [C1, C2, C3 ... Cn] 按受欢迎程度排序的前 N 个结果。
例如:
排除搜索引擎CE=[0]的TOP 3结果按热度排序为:
Domain | Category | Popularity
facebook.com | 1 | 23,943
youtube.com | 2 | 17,320
imdb.com | 3 | 6,094
排除除搜索引擎CE = [1, 2, 3, 4, 5]以外的所有类别的TOP 3结果按流行度排序为:
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
- 如何将排除的类别数组作为 WHERE 语句传递?
- 如何按人气升序/降序排序?
- 我是在 select 具有正确类别类型(性能方面)的那些之前还是之后订购它?
我不在乎响应是否按受欢迎程度排序。这是我可以 重做 客户端的东西。
我知道这是核心级别的东西,但有什么办法可以加快它的速度吗?毕竟是全table扫描!
select *
from websites
where Category in (1, 2, 3, 4, 5)
order by Popularity desc
limit 0,3;
将为您提供类别 1、2、3、4 或 5 中的 3 个最受欢迎的域
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 的最受欢迎的域
您可以使用 LIMIT
子句来做到这一点,您所要做的就是确保您的 WHERE
子句过滤掉您不想要的类别。试试这个:
SELECT *
FROM myTable
WHERE category NOT IN(category, list)
ORDER BY popularity DESC
LIMIT 3;
传递列表的方法是找到一种方法来构建要过滤掉的类别的逗号分隔列表。有关 IN
运算符的详细信息,请参阅 this link。
这是一个 SQL Fiddle 示例,其中显示了您的两个示例案例。