如何根据最大日期时间(另一列)选择不同的列,同时加入MySQL中的两个表?

时间:2013-05-13 04:27:34

标签: mysql join timestamp subquery distinct

我在这里阅读了许多类似的问题并尝试了我能想到的一切,但没有成功。我想我已经找到了基于单个表的问题,或者不需要获得不同的列,但不是我的情况。

我希望根据这些表格获得不同的ticker_symbol和相应的ticker_name以及最新的ticker_quote:

CREATE TABLE `tickers` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ticker_symbol` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `ticker_name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci



CREATE TABLE `ticker_quotes` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ticker_symbol` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `ticker_quote` float(8,2) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=111 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

1 个答案:

答案 0 :(得分:0)

尝试

SELECT q.ticker_symbol, t.ticker_name, q.ticker_quote
  FROM (SELECT ticker_symbol, MAX(created_at) created_at
          FROM ticker_quotes 
         GROUP BY ticker_symbol) m JOIN
       ticker_quotes q ON m.ticker_symbol = q.ticker_symbol 
                      AND m.created_at = q.created_at JOIN
       tickers t ON q.ticker_symbol = t.ticker_symbol

<强> SQLFiddle