同一张表省市县sql查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同一张表省市县sql查询相关的知识,希望对你有一定的参考价值。
一,表的结构
1 SELECT * FROM t_unionpay_areacode t
1 SELECT * FROM t_unionpay_areacode t WHERE t.`name`LIKE "%林州%";
1 SELECT * FROM t_unionpay_areacode t WHERE t.`parent_code`= ‘4960‘;
1 SELECT * FROM t_unionpay_areacode t WHERE t.code= ‘4960‘;
SELECT * FROM t_unionpay_areacode t WHERE t.`parent_code`=‘4900‘;
1 SELECT * FROM t_unionpay_areacode t WHERE t.code=‘4900‘;
从上面的sql语句我们可以的出来一个规律就是县的paraent_code是市,而市的parent_code是省,此外level还有1,2,3级之分,分别对应着省市县
二,联动查询
2.1,省市左外连接查询
1 SELECT 2 cy.NAME AS provice, 3 cy.CODE AS proviceCode, 4 ci.NAME AS city, 5 ci.CODE AS cityCode 6 7 FROM 8 t_unionpay_areacode cy 9 LEFT JOIN t_unionpay_areacode ci 10 ON ci.parent_code = cy.CODE 11 AND ci.LEVEL = 2 WHERE cy.NAME=‘河南省‘
2.2,市县左外查询
1 SELECT 2 cou1.NAME AS city, 3 cou1.CODE AS cou1Code, 4 cou2.NAME AS country, 5 cou2.CODE AS cou2Code 6 FROM 7 t_unionpay_areacode cou1 8 LEFT JOIN t_unionpay_areacode cou2 9 ON cou2.parent_code = cou1.CODE 10 AND cou2.LEVEL = 3 11 WHERE cou1.LEVEL = 2 AND cou1.NAME=‘安阳市‘
2.3,通过市的code或者name相同两个让省市的左外连接在左外连接市县的左外连接
1 SELECT 2 cy.NAME AS provice, 3 cy.CODE AS proviceCode, 4 ci.NAME AS city, 5 ci.CODE AS cityCode, 6 ct.country AS country, 7 ct.cou2Code AS countryCode 8 FROM 9 t_unionpay_areacode cy 10 LEFT JOIN t_unionpay_areacode ci 11 ON ci.parent_code = cy.CODE 12 AND ci.LEVEL = 2 13 LEFT JOIN 14 (SELECT 15 cou1.NAME AS city, 16 cou1.CODE AS cou1Code, 17 cou2.NAME AS country, 18 cou2.CODE AS cou2Code 19 FROM 20 t_unionpay_areacode cou1 21 LEFT JOIN t_unionpay_areacode cou2 22 ON cou2.parent_code = cou1.CODE 23 AND cou2.LEVEL = 3 24 WHERE cou1.LEVEL = 2) ct 25 ON ci.NAME = ct.city 26 WHERE cy.CODE = ‘4900‘ ;
以上是关于同一张表省市县sql查询的主要内容,如果未能解决你的问题,请参考以下文章