mysql - 按自定义条件排序值
问题描述
我有两个表 A 和 B 表:
表-A-代表人员的基本信息
emp_id | email | name
----------------------------------------
1 | abc@gmail.com | john
2 | dbc@gmail.com | john1
3 | cbc@gmail.com | john2
4 | xbc@gmail.com | john3
5 | xac@gmail.com | john4
表 - B 代表人员处理的位置
john 正在处理 Region 和 Zone john1 正在处理 Area 和 Territory 等等......
locationType 的顺序如下:Region->Zone->Area->Territory Regions 具有更高的优先级,然后是 zone,依此类推。
id | emp_id | locationType
--------------------
1 | 1 | Region
2 | 2 | Area
3 | 3 | Area
4 | 4 | Territory
5 | 1 | Zone
6 | 2 | Territory
7 | 5 | Zone
8 | 5 | Area
我想获取那些处理更高位置类型的人。假设 john 正在处理 Region 和 zone 所以我想显示 Region 因为 Region 具有更高的优先级,同样 john1 正在处理 Territory 和 Area 所以我只想显示 Area 因为 Area 具有更高的优先级
我想要的输出:
id | emp_id | name | locationType
----------------------------------------
1 | 1 | john | Region
5 | 5 | john4 | Zone
3 | 3 | john1 | Area
4 | 4 | john2 | Area
4 | 4 | john3 | Territory
我得到了什么
id | emp_id | name | locationType
----------------------------------------
1 | 1 | john | Region
1 | 1 | john | Zone
5 | 5 | john4 | Zone
5 | 5 | john4 | Area
2 | 2 | john1 | Area
3 | 3 | john2 | Area
4 | 4 | john3 | Territory
4 | 4 | john3 | Territory
解决方案
您可以使用field()
将位置转换为数字。您想要的是基于此排序的最小位置。
您可以使用相关子查询为每个员工获取此信息:
select b.*
from b
where field(b.locationType, 'Region', 'Zone', 'Area', 'Territory') =
(select min(field(b2.locationType, 'Region', 'Zone', 'Area', 'Territory'))
from b b2
where b2.emp_id = b.emp_id
);
添加额外的列a
只是加入表的问题。
推荐阅读
- javascript - 如何从 JavaScript 中的字符串字符获取 unicode 名称
- android - 长按后按下按钮时继续执行操作
- prolog - 使用最大值进行选择排序
- python - Tkinter:从画布中删除图像时出错
- google-sheets - 将列转换为行
- sql - 需要知道&&在这个查询中的作用
- php - 为什么我的 html 文件在 wordpress 侧边栏小部件中的回显会破坏其他小部件前端小部件样式?
- c++ - 如何在没有任务切换的情况下创建 QThread
- python - 使用 Pandas 聚合 JSON 对象中的相似字段
- memory-management - cython 内存不足