在sql查询MYSQL中限制结果

时间:2013-02-15 13:25:45

标签: mysql

我有一个包含以下字段的表格:

 id
 name
 date_created
 department

我希望按date_created

排序所有记录

但我希望每个部门只有2个结果。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

这样的事情应该有用 - 你需要得到你的行号,按部门分组:

SELECT Id, 
  Name, 
  Date_Created, 
  Department
FROM (
    SELECT @curRow:=CASE WHEN @prevRow = Department THEN @curRow+1 ELSE 1 END AS rn,
      Id, 
      Name, 
      Date_Created, 
      Department,
      @prevRow:=Department   clset
    FROM YourTable
      JOIN (SELECT @curRow:= 0) r
    ORDER BY Department, Date_Created DESC
  ) t
WHERE rn <= 2

还有一些示例Fiddle

答案 1 :(得分:-1)

select * from tablename
group by department
order by date_created
limit 0, 2