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

时间:2018-02-28 17:30:08

标签: mysql mysql-5.6

我有一个看起来像这样的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获取重复记录,对吗?

1 个答案:

答案 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 |

演示:http://sqlfiddle.com/#!9/d48b92/2