A question similar to this:
MySQL: subquery browsing in FROM article restriction
I have the following table shows:
DROP TABLE IF EXISTS `shows`;
CREATE TABLE `shows` (
`show_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`show_type` int(11) unsigned DEFAULT NULL,
`show_year` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`show_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `shows` VALUES
(NULL, 1, 2014),
(NULL, 1, 2015),
(NULL, 2, 2015),
(NULL, 2, 2014);
I want to create a VIEW that will return show_idfor the highest show_yearfor everyone show_type. Here's a nested query that works - returns 2 and 3:
SELECT s.show_id, s.show_year
FROM (
SELECT *
FROM shows
ORDER BY show_year DESC
) s
GROUP BY show_type;
For reference only, I also tried the following query, which at first seemed natural to me, but in my case it turned out to be bad , as shown below:
SELECT s.show_id, MAX(s.show_year)
FROM shows s
GROUP BY show_type;
Now create VIEW - based on the nested query above (first SELECT), the problem is that the view will not accept the subquery .
, . .
show_year DESC:
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `shows_desc` AS
SELECT `s1`.`show_id` AS `show_id`,
`s1`.`show_type` AS `show_type`,
`s1`.`show_year` AS `show_year`
FROM `shows` `s1`
ORDER BY `s1`.`show_year` DESC;
GROUP BY :
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `shows_grouped` AS
SELECT `s2`.`show_id` AS `show_id`,
`s2`.`show_year` AS `show_year`
FROM `shows_desc` `s2`
GROUP BY `s2`.`show_type`;
, , . GROUPed ORDER :
+---------+-----------+
| show_id | show_year |
+---------+-----------+
| 3 | 2015 |
| 1 | 2014 | <== why?
+---------+-----------+
?
P.S.: SQL : http://sqlfiddle.com/#!2/e506d4/5