---
title: "查询每一组的前N条记录"
author: "dreamoftch"
date: "2018-07-05T10:10:55Z"
tags: []
categories: ["数据库"]
slug: "n"
draft: false
lastmod: "2018-07-05T10:10:55Z"
id: 2426238
url: "https://dreamoftch.iteye.com/blog/2426238"
---

[参考链接](https://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/)

比如要查询每个人创建的前10条公司：

 

```
select a.*
from organization a 
where 
(select count(1) 
from organization b 
where a.created_by = b.created_by and b.id < a.id) < 10
```

> 通过表关联，从主表开始，逐条查询该记录在关联表中，有多少条结果的id更小(对应创建时间更早),然后关联表中满足条件的记录数少于10条则表明当前主表的记录是该created\_by创建的前10条记录