首页 > 解决方案 > 从与其他条件匹配的行中选择特定列中值最低的行

问题描述

我创建了一个 SQL 表来将事件数据保存到其中。

每个事件可以有多次出现,当我在现场过滤它们时 - 我希望每个事件的第一次匹配出现。每次出现都保存在不同的行中,其中包含用于一般 event_id 的列和每次出现的特定 occ_id。

我需要从匹配的行中获取 - 每个 event_id 只有一行,并且它必须是具有最低 occ_id 值的行。

IE

gen_id  | event_id | occ_id | month
------------------------------------
1       | 190      | 1      | 4    
2       | 190      | 2      | 4    
3       | 190      | 3      | 4    
4       | 192      | 1      | 4    
5       | 192      | 2      | 4    
6       | 192      | 3      | 4    
7       | 193      | 1      | 5    
8       | 193      | 2      | 5

如果我要查找月份 = 4 的事件,我需要获取事件 (gen_id): 1,4

如果我正在寻找月份 = 5 我只需要获取事件 (gen_id): 7

我的 SQL 查询现在获取匹配的事件,但没有 occ_id 过滤:

(现在看起来像这样)

SELECT
    event_id,
    event_title,
    occ_id
    FROM
    table_name
    WHERE month = 4
    GROUP BY event_id
    ORDER BY
    event_id
    DESC

我也尝试过使用 MIN / MAX 但我猜它要么不是这种情况下的正确处理程序,要么我用错了......

标签: phpmysqlsql

解决方案


你想过滤。一种方法在子句中使用相关子查询WHERE

select t.*
from table_name t
where t.occ_id = (select min(t2.occ_id)
                  from table_name t2
                  where t2.event_id = t.event_id
                 );

但是,最低值似乎总是“1”,所以这也可能有效:

select t.*
from table_name t
where t.month = 4 and
      t.occ_id = 1;

要添加month,您可以将其添加到外部查询中:

select t.*
from table_name t
where t.month = 4 and
      t.occ_id = (select min(t2.occ_id)
                  from table_name t2
                  where t2.event_id = t.event_id and
                        t2.month = t.month
                 );

推荐阅读