<legend id='1ZACO'><style id='1ZACO'><dir id='1ZACO'><q id='1ZACO'></q></dir></style></legend>
    • <bdo id='1ZACO'></bdo><ul id='1ZACO'></ul>
    <tfoot id='1ZACO'></tfoot>

    <small id='1ZACO'></small><noframes id='1ZACO'>

      <i id='1ZACO'><tr id='1ZACO'><dt id='1ZACO'><q id='1ZACO'><span id='1ZACO'><b id='1ZACO'><form id='1ZACO'><ins id='1ZACO'></ins><ul id='1ZACO'></ul><sub id='1ZACO'></sub></form><legend id='1ZACO'></legend><bdo id='1ZACO'><pre id='1ZACO'><center id='1ZACO'></center></pre></bdo></b><th id='1ZACO'></th></span></q></dt></tr></i><div id='1ZACO'><tfoot id='1ZACO'></tfoot><dl id='1ZACO'><fieldset id='1ZACO'></fieldset></dl></div>
    1. 检索每组中的最后一条记录 - MySQL

      时间:2023-08-19

        <small id='JlCRO'></small><noframes id='JlCRO'>

            <legend id='JlCRO'><style id='JlCRO'><dir id='JlCRO'><q id='JlCRO'></q></dir></style></legend>

              • <bdo id='JlCRO'></bdo><ul id='JlCRO'></ul>
                <tfoot id='JlCRO'></tfoot>
                  <tbody id='JlCRO'></tbody>
              • <i id='JlCRO'><tr id='JlCRO'><dt id='JlCRO'><q id='JlCRO'><span id='JlCRO'><b id='JlCRO'><form id='JlCRO'><ins id='JlCRO'></ins><ul id='JlCRO'></ul><sub id='JlCRO'></sub></form><legend id='JlCRO'></legend><bdo id='JlCRO'><pre id='JlCRO'><center id='JlCRO'></center></pre></bdo></b><th id='JlCRO'></th></span></q></dt></tr></i><div id='JlCRO'><tfoot id='JlCRO'></tfoot><dl id='JlCRO'><fieldset id='JlCRO'></fieldset></dl></div>
              • 本文介绍了检索每组中的最后一条记录 - MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                问题描述

                有一个表 messages 包含如下所示的数据:

                There is a table messages that contains data as shown below:

                Id   Name   Other_Columns
                -------------------------
                1    A       A_data_1
                2    A       A_data_2
                3    A       A_data_3
                4    B       B_data_1
                5    B       B_data_2
                6    C       C_data_1
                

                如果我运行一个查询select * from messages group by name,我会得到如下结果:

                If I run a query select * from messages group by name, I will get the result as:

                1    A       A_data_1
                4    B       B_data_1
                6    C       C_data_1
                

                什么查询会返回以下结果?

                What query will return the following result?

                3    A       A_data_3
                5    B       B_data_2
                6    C       C_data_1
                

                即返回每组最后一条记录.

                That is, the last record in each group should be returned.

                目前,这是我使用的查询:

                At present, this is the query that I use:

                SELECT
                  *
                FROM (SELECT
                  *
                FROM messages
                ORDER BY id DESC) AS x
                GROUP BY name
                

                但这看起来效率极低.还有其他方法可以达到相同的结果吗?

                But this looks highly inefficient. Any other ways to achieve the same result?

                推荐答案

                MySQL 8.0 现在支持窗口函数,就像几乎所有流行的 SQL 实现一样.使用这种标准语法,我们可以编写最大 n-per-group 查询:

                MySQL 8.0 now supports windowing functions, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries:

                WITH ranked_messages AS (
                  SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn
                  FROM messages AS m
                )
                SELECT * FROM ranked_messages WHERE rn = 1;
                

                以下是我在 2009 年为这个问题写的原始答案:

                Below is the original answer I wrote for this question in 2009:

                我是这样写解决方案的:

                I write the solution this way:

                SELECT m1.*
                FROM messages m1 LEFT JOIN messages m2
                 ON (m1.name = m2.name AND m1.id < m2.id)
                WHERE m2.id IS NULL;
                

                关于性能,一种解决方案或另一种解决方案可能更好,具体取决于数据的性质.因此,您应该测试这两个查询,并使用给定数据库性能更好的查询.

                Regarding performance, one solution or the other can be better, depending on the nature of your data. So you should test both queries and use the one that is better at performance given your database.

                例如,我有一份 StackOverflow 八月数据转储的副本.我将使用它进行基准测试.Posts 表中有 1,114,357 行.这是在我的 Macbook Pro 2.40GHz 上的 MySQL 5.0.75 上运行的.

                For example, I have a copy of the StackOverflow August data dump. I'll use that for benchmarking. There are 1,114,357 rows in the Posts table. This is running on MySQL 5.0.75 on my Macbook Pro 2.40GHz.

                我将编写一个查询来查找给定用户 ID(我的)的最新帖子.

                I'll write a query to find the most recent post for a given user ID (mine).

                首先使用技术显示 by @Eric 在子查询中使用 GROUP BY :

                First using the technique shown by @Eric with the GROUP BY in a subquery:

                SELECT p1.postid
                FROM Posts p1
                INNER JOIN (SELECT pi.owneruserid, MAX(pi.postid) AS maxpostid
                            FROM Posts pi GROUP BY pi.owneruserid) p2
                  ON (p1.postid = p2.maxpostid)
                WHERE p1.owneruserid = 20860;
                
                1 row in set (1 min 17.89 sec)
                

                即使是 EXPLAIN 分析 需要超过 16 秒:

                Even the EXPLAIN analysis takes over 16 seconds:

                +----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
                | id | select_type | table      | type   | possible_keys              | key         | key_len | ref          | rows    | Extra       |
                +----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
                |  1 | PRIMARY     | <derived2> | ALL    | NULL                       | NULL        | NULL    | NULL         |   76756 |             | 
                |  1 | PRIMARY     | p1         | eq_ref | PRIMARY,PostId,OwnerUserId | PRIMARY     | 8       | p2.maxpostid |       1 | Using where | 
                |  2 | DERIVED     | pi         | index  | NULL                       | OwnerUserId | 8       | NULL         | 1151268 | Using index | 
                +----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
                3 rows in set (16.09 sec)
                

                现在使用 我的技术与LEFT JOIN:

                Now produce the same query result using my technique with LEFT JOIN:

                SELECT p1.postid
                FROM Posts p1 LEFT JOIN posts p2
                  ON (p1.owneruserid = p2.owneruserid AND p1.postid < p2.postid)
                WHERE p2.postid IS NULL AND p1.owneruserid = 20860;
                
                1 row in set (0.28 sec)
                

                EXPLAIN 分析表明两个表都能够使用它们的索引:

                The EXPLAIN analysis shows that both tables are able to use their indexes:

                +----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
                | id | select_type | table | type | possible_keys              | key         | key_len | ref   | rows | Extra                                |
                +----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
                |  1 | SIMPLE      | p1    | ref  | OwnerUserId                | OwnerUserId | 8       | const | 1384 | Using index                          | 
                |  1 | SIMPLE      | p2    | ref  | PRIMARY,PostId,OwnerUserId | OwnerUserId | 8       | const | 1384 | Using where; Using index; Not exists | 
                +----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
                2 rows in set (0.00 sec)
                


                这是我的 Posts 表的 DDL:

                CREATE TABLE `posts` (
                  `PostId` bigint(20) unsigned NOT NULL auto_increment,
                  `PostTypeId` bigint(20) unsigned NOT NULL,
                  `AcceptedAnswerId` bigint(20) unsigned default NULL,
                  `ParentId` bigint(20) unsigned default NULL,
                  `CreationDate` datetime NOT NULL,
                  `Score` int(11) NOT NULL default '0',
                  `ViewCount` int(11) NOT NULL default '0',
                  `Body` text NOT NULL,
                  `OwnerUserId` bigint(20) unsigned NOT NULL,
                  `OwnerDisplayName` varchar(40) default NULL,
                  `LastEditorUserId` bigint(20) unsigned default NULL,
                  `LastEditDate` datetime default NULL,
                  `LastActivityDate` datetime default NULL,
                  `Title` varchar(250) NOT NULL default '',
                  `Tags` varchar(150) NOT NULL default '',
                  `AnswerCount` int(11) NOT NULL default '0',
                  `CommentCount` int(11) NOT NULL default '0',
                  `FavoriteCount` int(11) NOT NULL default '0',
                  `ClosedDate` datetime default NULL,
                  PRIMARY KEY  (`PostId`),
                  UNIQUE KEY `PostId` (`PostId`),
                  KEY `PostTypeId` (`PostTypeId`),
                  KEY `AcceptedAnswerId` (`AcceptedAnswerId`),
                  KEY `OwnerUserId` (`OwnerUserId`),
                  KEY `LastEditorUserId` (`LastEditorUserId`),
                  KEY `ParentId` (`ParentId`),
                  CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`PostTypeId`) REFERENCES `posttypes` (`PostTypeId`)
                ) ENGINE=InnoDB;
                


                评论者注意:如果您想使用不同版本的 MySQL、不同的数据集或不同的表设计进行另一个基准测试,请自行完成.我已经展示了上面的技术.Stack Overflow 是为了向您展示如何进行软件开发工作,而不是为您完成所有工作.

                这篇关于检索每组中的最后一条记录 - MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                上一篇:如何在 MySQL 中返回数据透视表输出? 下一篇:如何创建 MySQL 分层递归查询?

                相关文章

                最新文章

                  <bdo id='hvSXr'></bdo><ul id='hvSXr'></ul>

              • <small id='hvSXr'></small><noframes id='hvSXr'>

              • <legend id='hvSXr'><style id='hvSXr'><dir id='hvSXr'><q id='hvSXr'></q></dir></style></legend>

                  <tfoot id='hvSXr'></tfoot>
                  <i id='hvSXr'><tr id='hvSXr'><dt id='hvSXr'><q id='hvSXr'><span id='hvSXr'><b id='hvSXr'><form id='hvSXr'><ins id='hvSXr'></ins><ul id='hvSXr'></ul><sub id='hvSXr'></sub></form><legend id='hvSXr'></legend><bdo id='hvSXr'><pre id='hvSXr'><center id='hvSXr'></center></pre></bdo></b><th id='hvSXr'></th></span></q></dt></tr></i><div id='hvSXr'><tfoot id='hvSXr'></tfoot><dl id='hvSXr'><fieldset id='hvSXr'></fieldset></dl></div>