mybatis选择带有if条件的查询

9rnv2umw  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(429)

我有一张这样的table

+-------+-------+-------+-------+-------------+
| pkey1 | pkey2 | mode  | type  | type_number |
+-------+-------+-------+-------+-------------+
|   001 |    01 | light | type1 |        1234 |
|   001 |    02 | light | type2 |        2345 |
|   002 |    01 | dark  | type1 |        3456 |
|   002 |    02 | dark  | type2 |        4567 |
+-------+-------+-------+-------+-------------+

我有一个mybatis select查询伪代码

SELECT 
 Master.pkey1,
 Master.pkey2,
 Master.mode,
 Master.type,
 T1.selectedNumber type_number
FROM
( SELECT * from sample_table)
 as Master
left join (select type_number as selectedNumber from sample_table where type='type1') as T1
ON T1.pkey1 = Master.pkey1
left join (select type_number as selectedNumber from sample_table where type='type2') as T2
ON T2.pkey1 = Master.pkey1)

有没有办法根据模式中的值从t1或t2中进行选择,比如

SELECT 
 Master.pkey1,
 Master.pkey2,
 Master.mode,
 Master.type,
 if Master.type='light'
  T1.selectedNumber type_number
 if Master.type='dark'
  T2.selectedNumber type_number

我的预期结果是这样的

+-------+-------+-------+-------+-------------+
| pkey1 | pkey2 | mode  | type  | type_number |
+-------+-------+-------+-------+-------------+
|   001 |    01 | light | type1 |        1234 |
|   001 |    02 | light | type2 |        1234 |
|   002 |    01 | dark  | type1 |        4567 |
|   002 |    02 | dark  | type2 |        4567 |
+-------+-------+-------+-------+-------------+

编辑:添加了一些额外的代码和预期的结果

7hiiyaii

7hiiyaii1#

使用窗口函数怎么样?

select s.*,
       (case when mode = 'light'
             then max(case when type = 'type1' then type_number end) over (partition by pkey1)
             else max(case when type = 'type2' then type_number end) over (partition by pkey2)
       end)
from sample_table s;

相关问题