显示表1中上次更新条目的数据,并与table2中的信息结合使用

时间:2016-05-31 05:05:32

标签: mysql

我有两张桌子:

rankHistory ,它根据给定的关键字存储bookID的排名。 它的结构如下:

create table rankHistory (
id int(10),
rankUpdated timestamp,
bookId varchar(10),
keyword varchar(100),
rank int(5)
);

此表中包含的示例数据:

INSERT INTO rankHistory
(`id`, `rankUpdated`,`bookId`,`keyword`,`rank`)
VALUES
(1, '2016-05-27 05:11:44', 'BK-001','romantic','80'),
(2, '2016-05-28 08:11:44', 'BK-001','romantic','15'),
(3, '2016-05-28 09:11:44', 'BK-001','romantic','13'),
(4, '2016-05-27 07:11:44', 'BK-001','romantic book','77'),
(5, '2016-05-28 08:11:44', 'BK-001','romantic book','25'),
(6, '2016-05-28 09:11:44', 'BK-001','romantic book','22'),
(7, '2016-05-27 05:11:44', 'BK-002','horror','65'),
(8, '2016-05-28 08:11:44', 'BK-002','horror','10'),
(9, '2016-05-29 07:11:44', 'BK-002','horror book','25'),
(10, '2016-05-29 08:11:44', 'BK-002','horror book','9')
;

bookConfig 包含bookID的信息及其给定的关键字。 它的结构如下:

create table bookConfig (
id int(10),
category varchar(40),
author varchar(255),
info varchar (255)
);

此表中包含的示例数据:

INSERT INTO bookConfig
(`id`,`bookId`,`keyword`, `category`, `author`,`info`)
VALUES
(1, 'BK-001', 'romantic', 'Romance', 'Author1','Romance themed book written by author1'),
(2, 'BK-001', 'romantic book', 'Romance', 'Author1','Romance themed book written by author1'),
(3, 'BK-002', 'horror ', 'Horror', 'Author2','Horror themed book written by author2'),
(4, 'BK-002', 'horror book', 'Horror', 'Author2','Horror book written by author2')
 ;

我已将其合并到http://sqlfiddle.com/#!9/9502a9

rankHistory 包含与提供的数据类似的数万条记录,我的关注点也在于速度。结构可能从一开始就是错误的,但不幸的是,这是我必须处理的遗产。

我想要实现的目标如下:

为每个唯一的bookid /关键字组合选择具有最新时间戳的条目,然后加入与bookConfig中包含的该组合相关的信息。

所以期望的输出是:

rankUpdated          bookId  keyword      rank,category,author,  info
---------------------------------------------------------------------------- 
2016-05-28 09:11:44, BK-001, romantic,      13, romance, Author1, Romance themed book..
2016-05-28 09:11:44, BK-001, romantic book, 22, romance, Author1, Romance themed book..
2016-05-28 08:11:44, BK-002, horror,        10, horror,  Author2, Horror themed book..
2016-05-29 08:11:44, BK-002, horror book,    9, horror,  Author2, Horror book ...

我已经尝试了几种方法来实现这一目标但没有成功,并且失去了如何正确实现这一目标。如果有更精通mySQL的人能指出我实现这一目标的最佳方法,我将非常感激。

非常感谢您提前分享您的专业知识

1 个答案:

答案 0 :(得分:2)

一种选择是进行一系列连接以实现您的目标:

SELECT COALESCE(t2.rankUpdated, 'NA'), AS rankUpdated, t1.bookId, t1.keyword,
    COALESCE(t2.rank, 'NA') AS rank, t1.category, t1.author, t1.info
FROM bookConfig t1
LEFT JOIN
(
    SELECT r1.bookId, r1.rankUpdated, r1.rank, r1.keyword
    FROM rankHistory r1
    INNER JOIN
    (
        SELECT bookId, keyword, MAX(rankUpdated) AS rankUpdated
        FROM rankHistory
        GROUP BY bookId, keyword
    ) r2
        ON r1.bookId = r2.bookId AND r1.keyword = r2.keyword AND
           r1.rankUpdated = r2.rankUpdated
) t2
    ON t1.bookId = t2.bookId AND t1.keyword = t2.keyword

请按照以下链接查看正在运行的演示:

SQLFiddle