首页 > 解决方案 > 按自定义条件排序值

问题描述

我有两个表 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

标签: mysqlsqlselectsql-order-bymysql-workbench

解决方案


您可以使用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只是加入表的问题。


推荐阅读