我有一个看起来像这样的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
获取重复记录,对吗?
答案 0 :(得分:1)
我的答案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 |