2011-11-26 66 views
1

中填充区域字段是否可以填充存储在另一个字段中的数据的功能字段?我更好地解释我:在数据库中有一个字段“telnum”(电话号码),其中存储了带有国际前缀的telepnone号码。我可以使用php命令填充每个数字前缀的“country”字段吗?在电话前缀

这是数据库:

______________________________________________ 
    | id | telnum | name | country | 
    ---------------------------------------------- 
    | 01 | 003912377 | Smith |    | 
    | 02 | 004412345 | White |    | 
    | 03 | 005454321 | Lopez |    | 

的“PHP命令”应该关联到各个不同的前缀国名在我的SQL表。在这个例子中,我们有0039 - >意大利,0044 - >英国,0054 - >阿根廷......等等。 结果必须为:

______________________________________________ 
    | id | telnum | name | country | 
    ---------------------------------------------- 
    | 01 | 003912377 | Smith | Italy  | 
    | 02 | 004412345 | White | UK  | 
    | 03 | 005454321 | Lopez | Argentina | 

在此先感谢大家的帮助。 问候,马修

回答

1

您可以查询

update table 
set country = 
case 
when left(telnum,4) = 0039 then 'Italy' 
when left(telnum,4) = 0044 then 'UK' 
when left(telnum,4) = 0054 then 'Argentina' 
else '' 
end 
+0

嘿太感谢你了!我发现你的答案的代码非常简单而且有用,它完美地工作。我可以使用相同的脚本来填充更多的字段吗?例如,我希望在大陆的“eu”字段中添加意大利的前缀,“阿根廷的美国”等等。提前致谢。 – mattew

0

YES内使用case声明,

如果你已经有一个国家或地区代码映射
(这意味着另一个表COUNTRY_CODE + COUNTRY_NAME)
您可以执行INNER JOIN,如: -

select u.id, u.telnum, u.name, c.country_name 
from user as u 
inner join country c 
on left(u.telnum, 4) = c.country_code 
...; 

否则,你可以把映射到一个PHP配置文件,
与格式,与

$country_code = array(); 
$country_code['0039'] = ...; 

然后,当你遍历从MySQL结果,
你可以做映射相应

0

的MySQL查询方法:

UPDATE telcountry_table 
SET country = 
CASE 
    WHEN left(telnum,4) = 0093 THEN 'Afghanistan' 
    WHEN left(telnum,5) = 00355 THEN 'Albania' 
    WHEN left(telnum,5) = 00213 THEN 'Algeria' 
    . 
    . 
    . 
    ELSE '' 
END 

查询的完整版:https://gist.github.com/1395484#file_mysql_phoneprefix_to_zone_field.sql

PHP方式:

$call_code = array(); 
$call_code['93']='Afghanistan'; 
$call_code['355']='Albania'; 
$call_code['213']='Algeria'; 
. 
. 
. 

$func = function($value) { 
    $code2=substr($value['telnum'],2,2); 
    $code3=substr($value['telnum'],2,3); 
    $code4=substr($value['telnum'],2,4); 
    if(array_key_exists($code2,$call_code)) 
     $value['country']=$call_code[$code2]; 
    else if(array_key_exists($code3,$call_code)) 
     $value['country']=$call_code[$code3]; 
    else if(array_key_exists($code4,$call_code)) 
     $value['country']=$call_code[$code4]; 
    return $value; 
}; 

$countries=array_map($func,$data); 

脚本的完整版:https://gist.github.com/1395484#file_php_phoneprefix_to_zone_field.php

+0

非常感谢!正如我对另一位朋友所说的,我发现你的答案的代码非常简单而且有用,它完美地工作(我指的是你的nswer的“MySQL查询方式”)。我可以使用相同的脚本结构来填充更多的字段吗?例如,我希望在大陆的“eu”字段中添加意大利的前缀,“阿根廷的美国”等等。否则,我需要如何修改全局脚本(MyQSL方式)?提前致谢。 – mattew

+0

只需以相同的方式设置另一列:'country = CASE ... END'后加 ',continent = CASE **用大洲代码替换国家代码** END' – rogal111