如何在一次传球中抓住1条记录?

问题描述 投票:2回答:1

我有一个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获得重复记录,对吗?

mysql mysql-5.6
1个回答
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 |

但是:ぁzxswい

© www.soinside.com 2019 - 2024. All rights reserved.