Question

I'm going to phrase this in sentence form first and then in data form.

What I want to do in sentence from: "Show me three car manufacturers sorted by the the most recent to release a new car, along with all of the cars those manufacturers have made."

SO I want the data to come out something like this:

Ford, ModelA, 2012
Ford, ModelG, 2008
Toyota, ModelH, 2011
Toyota, ModelJ, 2009
Honda, ModelN, 2010
Hondda, ModelK, 2007

My problem is that when I try to order them together by manufacturer, it UNDOES the ordering by release date.

Ford, ModelA, 2012
Ford, ModelG, 2008
Honda, ModelN, 2010 <--wrong, Toyota should go here
Hondda, ModelK, 2007
Toyota, ModelH, 2011
Toyota, ModelJ, 2009

And if I don't try to order them together by manufacturer after getting release date, I get lines joined out of order depending on how they are ordered in the database.

Ford, ModelA, 2012
Honda, ModelN, 2010<--wrong, want to finish Fords before moving to next latest release
Ford, ModelG, 2008
Hondda, ModelK, 2007
Toyota, ModelH, 2011
Toyota, ModelJ, 2009

I've tried various attempts at INNER JOIN on a subquery like,

SELECT * FROM cars 
INNER JOIN (SELECT m.manufactuer 
            FROM cars AS m 
            ORDER BY m.year DESC LIMIT 3) subq 
ON cars.manufacturer=subq.object 
ORDER BY cars.manufacturer

(Some other attemts where insufficient because the LIMIT can't be used on all types of subquerys).

I'm open to splitting it up into mutiple querys.

+---------------+---------+--------+
|manufacturer   | model   | year   |
|---------------|---------|--------|
|ford           |modelA   |2008    |
|toyota         | modelS  |2010    |

EDIT:

kordirko's answer and some of my variations of it, return the manufactures in the correct order but the year is overridden by the subquery match. So it produces something like

Ford, ModelA, 2012
Ford, ModelG, 2012<--
Honda, ModelN, 2010
Hondda, ModelK, 2010<--
Toyota, ModelH, 2011
Toyota, ModelJ, 2011<-- wrong, need it to show actual year of model, not year from match of the most recent

SOLUTION

RIGHT JOIN seems to give a useable solution:

SELECT cars.manufacturer, cars.year FROM cars 
RIGHT JOIN (SELECT m.manufacturer FROM cars AS m ORDER BY m.year DESC LIMIT 3) subq 
ON cars.manufacturer=subq.manufacturer

Haven't put it through the full rigors, but seems to work in cursory test.

Was it helpful?

Solution

Try:

SELECT c.manufactuer,
       c.model,
       c.year,
       s.year As most_recent_year
FROM cars c
INNER JOIN (
  SELECT m.manufactuer, max(m.year) year
  FROM cars AS m 
  GROUP BY m.manufactuer
  ORDER BY year DESC LIMIT 3
) s
ON c.manufactuer=s.manufactuer 
ORDER BY s.year DESC, c.year DESC

demo: http://sqlfiddle.com/#!2/fac25/2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top