CREATE TABLE `buy` ( `id` varchar(50) NOT NULL COMMENT 'id', `buy_cost` int(11) NOT NULL COMMENT '购买花费', `buy_expirationDate` date NOT NULL COMMENT '过期日期', `buy_date` date NOT NULL, `buy_leaseTime` int(11) NOT NULL COMMENT '购买有效期', `user_id` varchar(50) NOT NULL COMMENT '用户id', `music_id` varchar(50) NOT NULL COMMENT '歌曲id', PRIMARY KEY (`id`,`user_id`,`music_id`), KEY `fk_user_has_music_music1_idx` (`music_id`), KEY `fk_user_has_music_user1_idx` (`user_id`), CONSTRAINT `fk_user_has_music_music1` FOREIGN KEY (`music_id`) REFERENCES `music` (`id`), CONSTRAINT `fk_user_has_music_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
先根据music_id将buy表中的数据分为一组,然后取这组中buy_expirationDate最靠后的数据。
SELECT a.* FROM buy a INNER JOIN (SELECT max( UNIX_TIMESTAMP(buy_expirationDate) ) max_date,music_id FROM buy GROUP BY music_id) b ON a.music_id = b.music_id AND UNIX_TIMESTAMP(a.buy_expirationDate) = b.max_date