【问题标题】:Select items from distinct categories, including articles with no category从不同类别中选择项目,包括没有类别的文章
【发布时间】:2016-02-06 05:10:50
【问题描述】:

这似乎很简单。我有一个文章表,其中包含与此问题相关的以下字段:

id - INTEGER(11) AUTO_INCREMENT
category_id - INTEGER(11) DEFAULT(-1)

当一篇文章有​​一个类别时,它的 ID 位于 category_id 字段中。当它没有类别时,该列的值为-1。

我想做的是从这个文章表中随机选择三篇不同类别的文章。仅此一项就很简单了:

SELECT id FROM articles GROUP BY category_id ORDER BY RAND() LIMIT 3; 

但是,我不想像前面的查询那样将没有类别的文章归为一个类别。也就是说,我想将每篇 category_id 为 -1 的文章视为单独的类别。我该怎么做?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以使用union 创建一个派生表,其中包含

    1. 每个非 -1 类别 1 个文章 ID
    2. -1 类别的所有文章 ID

    然后从该表中选择 3 个随机 id

    select id from (
        select id from articles
        where category_id <> -1
        group by category_id
        union all
        select id from articles
        where category_id = -1
    ) t order by rand() limit 3;
    

    正如 cmets 中所指出的,上面的查询可能会为每个类别 id 返回相同的文章 id。如果这是一个问题,您可以尝试下面的查询,但它可能会运行缓慢,因为它通过 rand() 两次对表进行排序。

    select id from (
        select id from (
            select id from articles
            where category_id <> -1
            order by rand()
        ) t 
        group by category_id
        union all
        select id from articles
        where category_id = -1
    ) t order by rand() limit 3;
    

    【讨论】:

    • 按类别分组的子查询可能不是很随机。选择是任意的,但如果表未更改,则从一个查询到下一个查询可能是一致的。
    • @Barmar 这是真的。我考虑过使查询真正随机但决定反对它,因为看起来这个查询已经很昂贵了。
    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2012-12-16
    • 2013-01-26
    • 2015-01-13
    • 2016-09-03
    相关资源
    最近更新 更多