zoukankan      html  css  js  c++  java
  • mysql 分组查询

    一、表结构

    --
    --
    表的结构 `client_status`
    --

    CREATE TABLE IF NOT EXISTS `client_status` (
    `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
    `client_id` mediumint(8) unsigned NOT NULL,
    `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    )

    --
    --
    转存表中的数据 `client_status`
    --

    INSERT INTO `client_status` (`id`, `client_id`, `addtime`) VALUES
    (3, 1, '2012-03-26 10:32:30'),
    (4, 1, '2012-03-26 10:30:31'),
    (5, 1, '2012-03-26 10:30:32'),
    (6, 2, '2012-03-26 10:30:33'),
    (7, 2, '2012-03-26 10:30:34'),
    (8, 4, '2012-03-26 10:30:35'),
    (9, 4, '2012-03-26 10:30:36'),
    (10, 3, '2012-03-26 10:30:37'),
    (11, 3, '2012-03-26 10:30:38');

    二、目的

    按client_id分组,查询每个client_id中离目前时间最近的记录。

    查询结果示意

    idclient_idaddtime
    3 1 2012-03-26 10:32:30
    7 2 2012-03-26 10:30:34
    11 3 2012-03-26 10:30:38
    9 4 2012-03-26 10:30:36

    三、解决方案

    方案1:

    SELECT * FROM (SELECT * FROM client_status ORDER BY addtime DESC )a GROUP BY client_id
    explain分析
    idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
    1 PRIMARY <derived2> ALL NULL NULL NULL NULL 9 Using temporary; Using filesort
    2 DERIVED client_status ALL NULL NULL NULL NULL 9 Using filesort

    方案2:

    SELECT * FROM client_status a WHERE NOT EXISTS (SELECT 1 FROM client_status WHERE a.client_id = client_id AND a.addtime < addtime)
    explain分析
    idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
    1 PRIMARY a ALL NULL NULL NULL NULL 9 Using where
    2 DEPENDENT SUBQUERY client_status ref client_id client_id 3 pdmon.a.client_id 1 Using where

    方案3:

    SELECT * FROM `client_status` WHERE addtime IN (SELECT max( addtime ) FROM client_status GROUP BY client_id )
    explain分析
    idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
    1 PRIMARY client_status ALL NULL NULL NULL NULL 9 Using where
    2 DEPENDENT SUBQUERY client_status index NULL client_id 3 NULL 1  


    如果有更高效的SQL,欢迎回复!

  • 相关阅读:
    51nod 1087 1 10 100 1000(找规律+递推+stl)
    51nod 1082 与7无关的数 (打表预处理)
    51 nod 1080 两个数的平方和
    1015 水仙花数(水题)
    51 nod 1003 阶乘后面0的数量
    51nod 1002 数塔取数问题
    51 nod 1001 数组中和等于K的数对
    51 nod 1081 子段求和
    51nod 1134 最长递增子序列 (O(nlogn)算法)
    51nod 1174 区间中最大的数(RMQ)
  • 原文地址:https://www.cnblogs.com/mybest/p/2418200.html
Copyright © 2011-2022 走看看