我有一个MySQL表,看起来像这样:
recordID | peopleID | AddressTypeID | Address | ActiveInd
10 | 102 | 1 | 4th Ave | 1
11 | 102 | 3 | 4th Ave | 1
12 | 203 | 3 | 5th Ave | 1
我试图在peopleID
级别获得AddressTypeID = 1
的记录,但如果不存在,那么获得AddressTypeID = 3
的记录。
所以结果集是这样的:
recordID | peopleID | AddressTypeID | Address | ActiveInd
10 | 102 | 1 | 4th Ave | 1
12 | 203 | 3 | 5th Ave | 1
我不认为coalesce
是答案,并考虑尝试一个大的case
声明,但我会使用case
获得重复记录,对吗?
我的答案here(处理故障转移语言)的修改版本:
select t.*
from mytable t
left join mytable t1
on t1.peopleID = t.peopleID
and t1.AddressTypeID = 1
and t.AddressTypeID = 3
where t.AddressTypeID in (1, 3)
and t1.recordID is null
我更改了示例数据以涵盖更多案例:
| recordID | peopleID | AddressTypeID | Address | ActiveInd |
|----------|----------|---------------|---------|-----------|
| 10 | 102 | 1 | 4th Ave | 1 |
| 11 | 102 | 3 | 4th Ave | 1 |
| 12 | 203 | 3 | 5th Ave | 1 |
| 13 | 304 | 1 | 6th Ave | 1 |
| 14 | 405 | 2 | 7th Ave | 1 |
结果是:
| recordID | peopleID | AddressTypeID | Address | ActiveInd |
|----------|----------|---------------|---------|-----------|
| 10 | 102 | 1 | 4th Ave | 1 |
| 12 | 203 | 3 | 5th Ave | 1 |
| 13 | 304 | 1 | 6th Ave | 1 |
但是:ぁzxswい