如何在MySQL中查询以下内容?

时间:2012-08-15 14:01:03

标签: mysql sql database

我想从名为cars的表中返回3行,每辆车应该有一个不同的dealer_id,我希望它们按ID desc排序(这样最新的三辆车添加到数据库中的是返回的)

SELECT id,dealer_id,name,model_year 
FROM cars 
GROUP by dealer_id 
ORDER BY id DESC 
LIMIT 3; 

但是这个查询并没有从每个不同的dealer_id

返回最新的3辆车

1 个答案:

答案 0 :(得分:4)

如果您想要最新的记录,那么您可以使用以下内容:

SELECT c1.id, 
  c1.dealer_id, 
  c1.name, 
  c1.model_year, 
  c1.date_Added
FROM cars c1
inner join
(
  select dealer_id, max(date_Added) mxdate
  from cars
  group by dealer_id
) c2
  on c1.dealer_id= c2.dealer_id
  and c1.date_Added = c2.mxdate
GROUP BY dealer_id
ORDER BY id desc
LIMIT 3;

请参阅SQL Fiddle with Demo