php - 从与其他 critarias 匹配的行中选择特定列中具有最低值的行

标签 php mysql sql

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

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

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

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

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

如果我正在寻找 month = 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,但我猜它不是这种情况下的正确处理程序,或者我用错了......

最佳答案

您想过滤。一种方法是在 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
                 );

关于php - 从与其他 critarias 匹配的行中选择特定列中具有最低值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611348/

相关文章:

PHP & MySql Join 重复值

sql - 内联标量函数 : real or vaporware?

php - 如何在 PHP 中表示乘法

php - Codeigniter 查询生成器具有带有 IN 语句的子句

javascript - Jquery val() 无法读取 php echo 接收到的 html 标签

php - PHP的ob_start可以多次调用吗?

php - 防止用户执行两次操作

php - 如何创建等级系统

mysql - SQL查询-员工ID

mysql - 将 SELECT 变量连接到不同的表列 |遵循建议