码迷,mamicode.com
首页 > 数据库 > 详细

同一张表省市县sql查询

时间:2017-11-13 00:23:40      阅读:509      评论:0      收藏:0      [点我收藏+]

标签:alt   一个   bsp   sql语句   河南   河南省   外连接   nbsp   image   

一,表的结构

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查询

标签:alt   一个   bsp   sql语句   河南   河南省   外连接   nbsp   image   

原文地址:http://www.cnblogs.com/qingruihappy/p/7823333.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!