【问题标题】:How do I get the first n records, per foreign key with MySQL?如何使用 MySQL 获取每个外键的前 n 条记录?
【发布时间】:2021-03-15 19:20:37
【问题描述】:

我有下表:

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

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

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

【问题讨论】:

  • “之前”是什么意思? sql 数据没有任何内在顺序,您必须准确指定您想要的内容

标签: mysql sql subquery sql-order-by where-clause


【解决方案1】:

如果您运行的是 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

在所有版本中,您都可以使用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'
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2021-09-01
    • 2018-11-09
    相关资源
    最近更新 更多