I've read many somewhat similar questions here and tried everything I can think of, without success. I think I've found the question based on a single table, or without the need for getting a distinct column, but not my situation exactly.
I want to get distinct ticker_symbol and corresponding ticker_name and latest ticker_quote based on these tables:
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
Try
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.