我只需要从employee_leaves表中 for each 员工(employee_id)提取一条记录,但前提是status_id等于以下数字之一:7, 4, 3(按优先级写入).如果尚未找到第status_id=7行,则应查找第status_id=4行.如果未找到,则应查找第status_id=3行.

示例:应返回id=4的行

id employee_id status_id
1 7 1
2 7 2
3 7 4
4 7 7
9 7 3
27 7 7

推荐答案

First filter the rows of each employee_id for the status_ids that you want.
Then rank the rows with ROW_NUMBER() window function by applying the priorities that you want.
Finally pick the first row from each ranking:

WITH cte AS (
  SELECT *,
         ROW_NUMBER() OVER (
           PARTITION BY employee_id
           ORDER BY status_id = 7 DESC,
                    status_id = 4 DESC,
                    status_id = 3 DESC, -- this is the last option and it is actually not needed
                    id
         ) AS rn 
  FROM employee_leaves 
  WHERE status_id IN (7, 4, 3)
)
SELECT id, employee_id, status_id 
FROM cte 
WHERE rn = 1;

使用函数FIELD()可以简化ROW_NUMBER()内的ORDER BY子句:

ORDER BY FIELD(status_id, 7, 4, 3),
         id

或功能FIND_IN_SET():

ORDER BY FIND_IN_SET(status_id, '7,4,3'),
         id

See the demo.

Mysql相关问答推荐

MariaDB字段+1

可以优化这个带有重复WHERE子句的查询吗?

将类图转换为SQL数据库

时间戳上滚动窗口的 SQL 计数不同

SQL查询以查找两个特定行的总和

高效的 SQL 查询,用于计算半小时时间序列中已发生的行的一部分

如何编写一个查询,计算表中每个日期的一个日期加上前 4 天的记录数?

在 MySQL 中跨日期和位置计算和排序实体的共现

我在 mysql 查询中需要帮助,我想在年龄之间按年龄过滤器分组,并显示 0 计数之间找不到的数据

如何根据 R 中的价格范围将数据从一列复制到新列?

将sql查询转换为sequelize

MySQL 使用了错误的索引

Select 在同一天售出不同活动门票的收银员

使用 MySQL 在树中查找 Leaf

如何根据特定条件从mysql数据库中 Select 查询

如何通过一个查询批量更新 mysql 数据?

MYSQL_ROOT_PASSWORD 已设置但在 docker 容器中获取用户'root'@'localhost'的访问被拒绝(使用密码:YES)

Mysql中int(10)的最大大小是多少

为什么在 MySQL 中使用外键约束?

按 COUNT(*) 过滤?