我将首先以句子形式对此进行短语,然后以数据形式。
我想在句子中做什么: “让我看看三家汽车制造商按最新发布的新车排序, 以及这些制造商制造的所有汽车。“
所以我想要的数据是这样的:
Ford, ModelA, 2012
Ford, ModelG, 2008
Toyota, ModelH, 2011
Toyota, ModelJ, 2009
Honda, ModelN, 2010
Hondda, ModelK, 2007
我的问题是,当我尝试由制造商一起订购时,它会按发布日期排序。
Ford, ModelA, 2012
Ford, ModelG, 2008
Honda, ModelN, 2010 <--wrong, Toyota should go here
Hondda, ModelK, 2007
Toyota, ModelH, 2011
Toyota, ModelJ, 2009
如果我在发布日期之后没有尝试由制造商一起订购, 我根据数据库中的排序方式得到了无序连接线。
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
我已尝试在子查询上对INNER JOIN进行各种尝试,例如
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
(其他一些不足之处因为LIMIT不能用于所有类型的subquerys)。
我愿意把它分成多个查询。
+---------------+---------+--------+
|manufacturer | model | year |
|---------------|---------|--------|
|ford |modelA |2008 |
|toyota | modelS |2010 |
修改
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
解
RIGHT JOIN似乎提供了一个有用的解决方案:
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
没有完全严格,但似乎在粗略测试。
答案 0 :(得分:0)
尝试:
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