将同一行中相同网址对应的电话号码分组

时间:2015-02-05 16:34:25

标签: mysql sql xampp

在数据库中有一些相等的行,只改变电话号码。我想分组成对应于相同网址的单行电话号码,以获得第二个表格。我想知道是否有办法在mysql中使用一个或多个查询或其他方法执行此操作。提前致谢

Database1
    Url    |Company Name| Address |  City |ZipCode|PHONE
www.aaa.com|         AAA|StreetAAA|CityAAA|  00000|0000000000
www.aaa.com|         AAA|StreetAAA|CityAAA|  00000|1111111111
www.aaa.com|         AAA|StreetAAA|CityAAA|  00000|2222222222
www.bbb.com|         BBB|StreetBBB|CityBBB|  11111|3333333333
www.ccc.com|         CCC|StreetCCC|CityCCC|  22222|4444444444
www.ccc.com|         CCC|StreetCCC|CityCCC|  22222|5555555555
www.ccc.com|         CCC|StreetCCC|CityCCC|  22222|6666666666
www.ddd.com|         DDD|StreetDDD|CityDDD|  33333|7777777777
www.ddd.com|         DDD|StreetDDD|CityDDD|  33333|8888888888
www.eee.com|         EEE|StreetEEE|CityEEE|  44444|9999999999

Final Database to generate:
    Url    |Company Name| Address |  City |ZipCode|  PHONE1  |  PHONE2  |  PHONE3
www.aaa.com|         AAA|StreetAAA|CityAAA|  00000|0000000000|1111111111|2222222222
www.bbb.com|         BBB|StreetBBB|CityBBB|  11111|3333333333|          |
www.ccc.com|         CCC|StreetCCC|CityCCC|  22222|4444444444|5555555555|6666666666
www.ddd.com|         DDD|StreetDDD|CityDDD|  33333|7777777777|8888888888|
www.eee.com|         EEE|StreetEEE|CityEEE|  44444|9999999999|          |

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是将所有手机放入以逗号分隔的列表中:

select url, companyname, address, city, zipcode,
       group_concat(phone) as phones
from database1
group by url, companyname, address, city, zipcode;

但是,这并不是你想要的。如果所有群组都有三个电话号码,则以下内容会更加接近:

select url, companyname, address, city, zipcode,
       substring_index(group_concat(phone), ',', 1) as phone1,
       substring_index(substring_index(group_concat(phone), ',', 2), ',', -1) as phone2,
       substring_index(group_concat(phone), ',', -1) as phone3
from database1
group by url, companyname, address, city, zipcode;

所以,以下修复了这个问题:

select url, companyname, address, city, zipcode,
       (case when count(phone) >= 1
             then substring_index(group_concat(phone), ',', 1)
        end) as phone1,
       (case when count(phone) >= 2
             then substring_index(substring_index(group_concat(phone), ',', 2), ',', -1) 
        end) as phone2,
       (case when count(phone) >= 3
             then substring_index(group_concat(phone), ',', -1)
        end) as phone3
from database1
group by url, companyname, address, city, zipcode;