MySQL 如果未找到特定记录,则查询获取默认记录
MySQL query for getting default record if specific record is not found
我想要一个table能够存储团队特定值的,如果没有找到记录,将返回默认记录。
表名:产品
ProdID ProdName Team
1 AAA <NULL>
1 AAA_T1 T1
2 BBB <NULL>
3 CCC <NULL>
3 CCC_T1 T1
3 CCC_T2 T2
4 DDD <NULL>
4 DDD_T3 T3
查询需要Team传入,返回所有Products
T1 队
ProdID ProdName
1 AAA_T1
2 BBB
3 CCC_T1
4 DDD
T2 队
ProdID ProdName
1 AAA
2 BBB
3 CCC_T2
4 DDD
T3 队
ProdID ProdName
1 AAA
2 BBB
3 CCC
4 DDD_T3
我该如何实现?我需要更改 table 结构吗?
与NOT EXISTS
:
select distinct p.prodname
from products p
where p.team = 'T1'
or (
p.team is null
and not exists (
select 1 from products
where prodid = p.prodid and team = 'T1'
)
)
如果没有重复,您可以删除 distinct
。
参见 demo.
或者使用条件聚合:
select max(case when team = 'T1' or team is null then prodname end) prodname
from products
group by prodid
参见demo。
结果:
> | prodname |
> | :------- |
> | AAA_T1 |
> | BBB |
> | CCC_T1 |
> | DDD |
我想要一个table能够存储团队特定值的,如果没有找到记录,将返回默认记录。
表名:产品
ProdID ProdName Team
1 AAA <NULL>
1 AAA_T1 T1
2 BBB <NULL>
3 CCC <NULL>
3 CCC_T1 T1
3 CCC_T2 T2
4 DDD <NULL>
4 DDD_T3 T3
查询需要Team传入,返回所有Products
T1 队
ProdID ProdName
1 AAA_T1
2 BBB
3 CCC_T1
4 DDD
T2 队
ProdID ProdName
1 AAA
2 BBB
3 CCC_T2
4 DDD
T3 队
ProdID ProdName
1 AAA
2 BBB
3 CCC
4 DDD_T3
我该如何实现?我需要更改 table 结构吗?
与NOT EXISTS
:
select distinct p.prodname
from products p
where p.team = 'T1'
or (
p.team is null
and not exists (
select 1 from products
where prodid = p.prodid and team = 'T1'
)
)
如果没有重复,您可以删除 distinct
。
参见 demo.
或者使用条件聚合:
select max(case when team = 'T1' or team is null then prodname end) prodname
from products
group by prodid
参见demo。
结果:
> | prodname |
> | :------- |
> | AAA_T1 |
> | BBB |
> | CCC_T1 |
> | DDD |