如何使用 MySQL 获取每个外键的前 n 条记录?

How do I get the first n records, per foreign key with MySQL?

我有以下 table:

+----+-----------+------+
| id | table2_id | type |
+----+-----------+------+
|  1 |       100 | A    |
|  2 |       100 | B    |
|  3 |       100 | C    |
|  4 |       100 | A    |
|  5 |       250 | A    |
+----+-----------+------+

我需要一个 select 语句来获取第一次出现类型 C 之前的所有记录,根据 table2_id。 所以我想要记录 1、2 和 5

我会在带有循环的代码中执行此操作,但我需要在 MySQL 中专门执行此操作。

如果你是 运行 MySQL 8.0,你可以用 window 函数来做到这一点:

select *
from (
    select t.*, 
        min(case when type = 'C' then id end) over(partition by table2_id) min_id
    from mytable t
) t
where min_id is null or id < min_id

在所有版本中,您可以使用 not exists:

select t.*
from mytable t
where not exists (
    select 1
    from mytable t1
    where t1.table2_id = t.table2_id and t1.id <= t.id and t1.type = 'C'
)