我有一个包含3个电话列的表,我需要运行一些魔法试图获取一些电话号码可以匹配的记录,问题是电话号码可能位于2条记录之间的不同字段上。
所以我认为一个带有3个电话号码的规范字符串应该允许我进行比较,问题是封装过程。有没有办法做到这一点?我正在添加一个片段来说明我需要做什么。
表是:
╔═════╦══════════╦══════════╦══════════╗
║ ID ║ Phone1 ║ Phone2 ║ Phone3 ║
╠═════╬══════════╬══════════╬══════════╣
║ 123 ║ 555-1234 ║ 666-1235 ║ ║
║ 124 ║ 666-1235 ║ ║ 555-1234 ║
║ 125 ║ 555-8520 ║ 777-7410 ║ 444-9999 ║
╚═════╩══════════╩══════════╩══════════╝
我要找的结果是
╔═════╦══════════════════════════════╗
║ ID ║ ConcatPhones ║
╠═════╬══════════════════════════════╣
║ 123 ║ 555-1234||666-1235 ║
║ 124 ║ 555-1234||666-1235 ║
║ 125 ║ 444-9999||555-8520||777-7410 ║
╚═════╩══════════════════════════════╝
无论如何,我可以通过简单的CONCAT_WS变体或高效的存储过程来实现这一目标吗?
答案 0 :(得分:0)
如果值确实为NULL且不为空,则以下内容应该有效:
select id,
concat_ws('||', Phone1, Phone2, Phone3)
from t
引用为here:
CONCAT_WS()不会跳过空字符串。但是,它确实跳过了 分隔符参数后的NULL值。
为了处理订购,我会选择:
select id,
group_concat(phone Separator '||' order by phone) as ConcatPhones
from (select t.id,
(case when nums.n = 1 then phone1
when nums.n = 2 then phone2
when nums.n = 3 then phone3
end) as phone
from t cross join
(select 1 as n union all select 2 union all select 3) nums
) p
where phone is not null
group by id
这将过滤掉任何没有电话号码的ID。
你也可以用一个巨大的case
声明做到这一点,虽然这似乎是一场噩梦:
select t.id,
(case when phone1 < phone2 and phone2 < phone3 then concat_ws('||', phone1, phone2, phone3)
when phone1 < phone3 and phone3 < phone2 then concat_ws('||', phone1, phone3, phone2)
. . . through the remaining 4 permuatiations when all three are present
when phone1 is null and phone2 < phone3 then concat_ws('||', phone2, phone3)
. . . through the remaining 5 permutuations when one is NULL
when phone1 is null and phone2 is null then phone3
. . . through the remaining 2 permutations when two are NULL
end) as ConcatPhones
from t
这更有效率。 3个电话号码是可行的。我不想处理它们中的五个。