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

如何使用MySQL获取每个外键的前n条记录?,mysql,sql,subquery,sql-order-by,where-clause,Mysql,Sql,Subquery,Sql Order By,Where Clause,我有下表: +----+-----------+------+ | id | table2_id | type | +----+-----------+------+ | 1 | 100 | A | | 2 | 100 | B | | 3 | 100 | C | | 4 | 100 | A | | 5 | 250 | A | +----+-----------+------+ 我需要一个sel

我有下表:

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

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


我会在代码中使用循环来实现这一点,但我需要在MySQL中实现这一点。

如果您运行的是MySQL 8.0,则可以使用窗口函数来实现这一点:

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

“之前”是什么意思?sql数据没有任何内在顺序,您必须准确地指定您想要的工作方式。谢谢
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'
)