朋友今天问我一个问题:有两张数据表 bureau_area_code 和 county_code,我想用town_code截取前6位去和county_code截取前6位查询,查到对应的county_name该咋写?
下面先是两张表结构:
1 CREATE TABLE `bureau_area_code` ( 2 `ID` int(10) unsigned NOT NULL AUTO_INCREMENT, 3 `TOWN_CODE` text, 4 `TOWN_NAME` text, 5 `PROVINCE_CODE` varchar(255) DEFAULT NULL, 6 `PROVINCE_NAME` varchar(255) DEFAULT NULL, 7 `CITY_CODE` varchar(255) DEFAULT NULL, 8 `CITY_NAME` varchar(255) DEFAULT NULL, 9 `COUNTY_CODE` varchar(255) DEFAULT NULL, 10 `COUNTY_NAME` varchar(255) DEFAULT NULL, 11 PRIMARY KEY (`ID`) 12 )
1 CREATE TABLE `county_code` ( 2 `ID` int(10) unsigned NOT NULL AUTO_INCREMENT, 3 `COUNTY_CODE` text, 4 `COUNTY_NAME` text, 5 PRIMARY KEY (`ID`) 6 );
bureau_area_code 的数据是这样的:
county_code 的数据是这样的:
下面上代码:
1 update bureau_area_code, county_code 2 set bureau_area_code.COUNTY_NAME = county_code.COUNTY_NAME, 3 bureau_area_code.COUNTY_CODE = county_code.COUNTY_CODE 4 where LEFT(bureau_area_code.TOWN_CODE, 6) = LEFT(county_code.COUNTY_CODE, 6);
这里用到了 mysql 的内部函数 left,可以直接截取字符串。所以 where 的时候就直接使用 left 函数比较截取完的前6位就行。
要注意:数据源的那张表 county_code 也要在 update 中注册一下,不然会有 Unknown column 的错误。