【问题标题】:mysql query to get items from 3 typesmysql查询从3种类型中获取项目
【发布时间】:2021-01-01 22:12:34
【问题描述】:

我有一个 mysql 表,其中包含 3 种数据类型(文本、图像、视频)$type 列保存数据的类型。 (type = 1 表示文本,2 表示图像,3 表示视频)

以前我只是按位置排列了 18 条记录

SELECT * FROM tbl_news WHERE news_status=1 AND show_timeline = 1 ORDER BY position DESC LIMIT $start, 18

现在我的要求是需要从表中获取 18 条记录,它应该有 6 个文本、6 个图像和 6 个支持分页的视频。

输出应该是 (文字,图片,视频,文字,图片,视频,文字,图片,视频,文字,图片,视频,文字,图片,视频,文字,图片,视频)

【问题讨论】:

    标签: sql mariadb sql-order-by greatest-n-per-group window-functions


    【解决方案1】:

    如果您运行的是 MySQL 8.0,您可以为此使用窗口函数:

    select *
    from (
        select n.*, row_number() over(partition by type order by position desc) rn 
        from tbl_news n
        where news_status = 1 and show_timeline = 1 
    ) n
    where rn <= 5
    order by rn, type
    

    在早期版本中,一种(相当低效的)方法使用子查询:

    select n.*
    from tbl_news n
    where 
        news_status = 1 
        and show_timeline = 1 
        and (
            select count(*) 
            from tbl_news n1 
            where 
                n1.type = n.type 
                and n1.news_status = n.news_status 
                and n1.show_timeline = n.show_timeline
                and n1.position <= n.position
        ) <= 5
    

    【讨论】:

    • 我的服务器版本:10.1.44-MariaDB-0ubuntu0.18.04.1 - Ubuntu 18.04
    • @binuj - 10.2 有 ROW_NUMBER() 等。是时候升级了。
    • @binuj:直到你升级......我用早期版本的解决方案更新了我的答案。
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多