Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Bestellen Sie vor CONCAT_WS

Folgendes sollte funktionieren, wenn die Werte tatsächlich NULL und nicht leer sind:

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

Die Referenz ist hier :

Um die Bestellung abzuwickeln, würde ich gehen für:

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

Dadurch werden alle IDs herausgefiltert, die keine Telefonnummer haben.

Sie können dies auch mit einem riesigen case tun Aussage, obwohl das wie ein Alptraum erscheint:

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

Das ist effizienter. Es ist für 3 Rufnummern machbar. Ich würde mich nicht mit, sagen wir, fünf von ihnen befassen wollen.