MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
Te11UA
V2EX  ›  MySQL

请教一个极值差值且最小值需在最大值创建时间前的问题

  •  
  •   Te11UA · Jul 3, 2021 · 1706 views
    This topic created in 1806 days ago, the information mentioned may be changed or developed.

    基于 Mysql 5.7 ,想要做的效果是查看商品上升排名最多的商品

    表结构如下,每 10 分钟打点一次,记录商品排名:

    create table product_info
    (
        prodcut_name          varchar(16)                        null comment '商品名',
        total_index   smallint                           null comment '总排名',
        create_time   datetime default CURRENT_TIMESTAMP not null comment '创建时间'
    );
    

    本来想用

    SELECT prodcut_name, max(total_index) - min(total_index) AS index_diff
    FROM product_info
    WHERE create_time > '2021-07-01 00:00:00'
    GROUP BY prodcut_name
    ORDER BY index_diff DESC
    limit 10;
    

    但是发现这个只是考虑了差值,没有考虑到最大值的时间必须在最小值的时间前,这样写会下降排名最多的也会显示。这下 SQL 语句不会写了,思来想去只能分个语句写,想请问下有没有可写在一条的语句呢?

    1 replies    2021-07-04 01:30:34 +08:00
    isofew
        1
    isofew  
       Jul 4, 2021 via Android
    不做 group,商品自己和自己 join,条件是商品名一致且一个时间在另一个前,然后按排名差
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3015 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 09:16 · PVG 17:16 · LAX 02:16 · JFK 05:16
    ♥ Do have faith in what you're doing.