我遇到了一个“复杂”选择的问题。我有不同的表(每年一个),它们看起来像:
去年:
ShortName LongName Year
Nam1 Name One 2016
Nam2 Name Two 2016
...
Namn Name N 2016
2015年
ShortName LongName Year
Nam1 Name AltOne 2015
Nam4 Name AltFour 2015
...
Namn Name AltN 2015
也就是说,当一个人在两年(或更长时间)内出现时,观察值具有相同的ShortName,但LongName可能每年都不同。这些个体可能(也可能不)在这些年中重复出现。
我想为所有表中的所有个人选择最新的LongName。我的意思是,个人Nam1将于2016年和2015年面世。我想选择她最后一个可用的LongName,即'Name One‘。这同样适用于Nam2。
Nam4不会在2016年出现,但会在2015年出现,所以我想选择'Name AltFour‘。
最后的选择将是:
ShortName LongName Year
Nam1 Name One 2016
Nam2 Name Two 2016
Nam4 Name AltFour 2015
Namn Name N 2016
我有2016到2013年的表格。非常感谢你的帮助。
发布于 2016-08-04 18:09:41
像这样的东西应该是有效的:
-- Create a temporary singular table of the shared fields.
-- Ideally, the actual table probably should've looked something like this.
DROP TEMPORARY TABLE IF EXISTS tmpAll;
CREATE TEMPORARY TABLE `tmpAll`
SELECT ShortName, LongName, `Year` FROM table2016
UNION SELECT ShortName, LongName, `Year` FROM table2015
UNION SELECT ShortName, LongName, `Year` FROM table2014
UNION SELECT ShortName, LongName, `Year` FROM table2013
;
-- Find the most recent years for each name.
-- This could have just been a subquery of the next/last query; but...
-- MySQL does not support queries that reference a TEMPORARY table more than once.
DROP TEMPORARY TABLE IF EXISTS tmpRecents;
CREATE TEMPORARY TABLE `tmpRecents`
SELECT Shortname, MAX(`Year`) AS `Year`
FROM tmpAll
GROUP BY ShortName
;
-- Get the tmpAll records for the most recent year of each ShortName
SELECT tmpAll.*
FROM tmpAll INNER JOIN `tmp` USING (ShortName, `Year`)
;
-- You can DROP the temporary tables here, or
-- they will just go away when the connection is closed.
如果它很慢,您可以向临时表添加一个(ShortName
,Year
)索引。
https://stackoverflow.com/questions/38773858
复制相似问题