mysql - 在 CONCAT_WS 之前订购

标签 mysql concatenation

我有一个包含 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 的简单变体或高效存储过程来做到这一点?

最佳答案

如果值确实为 NULL 而不是空白,则以下内容应该有效:

select id,
       concat_ws('||', Phone1, Phone2, Phone3)
from t

引用是here :

CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

为了处理订单,我会去:

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个电话号码是可行的。我不想与其中的五个人打交道。

关于mysql - 在 CONCAT_WS 之前订购,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773804/

相关文章:

r - 连接数据框的行

python - 如何将 2D 数组连接到每个 3D 数组中?

使用 concat 和 union 的 MySQL 查询不起作用

mysql - sql 将产品所有者表分组,其中包含主要所有者和串联的次要所有者的列

mysql - 在 MySQL 数据库中将数据存储为数字与字符串值

mysql - 每周显示数据

java - 如何使用 Java 8 中的方法引用连接 String ArrayList 的所有元素

MySQL 数据库迁移在 Rails 上失败

mysql - 如何根据 CASE 语句的值编写 WHERE 语句?

php - 查询数据库时出错