根據區欄位id值查市和省(適用主表有一個縣的id值)
阿新 • • 發佈:2021-01-26
技術標籤:mysql
資料庫中建立表
建立資料庫中的程式碼如下
/*
SQLyog Ultimate v13.1.1 (64 bit)
MySQL - 5.5.25a
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
create table `address` (
`id` int (11) primary key auto_increment,
`name` varchar (60),
`pid` int (11)
);
insert into `address` ( `id`, `name`, `pid`) values('1','河南省','0');
insert into `address` (`id`, `name`, `pid`) values('2','陝西省','0');
insert into `address` (`id`, `name`, `pid`) values('3','山東省','0');
insert into `address` (`id`, `name`, `pid`) values('4','鄭州市','1');
insert into `address` (`id`, `name`, `pid`) values('5','開封市' ,'1');
insert into `address` (`id`, `name`, `pid`) values('6','西安市','2');
insert into `address` (`id`, `name`, `pid`) values('7','延安市','2');
insert into `address` (`id`, `name`, `pid`) values('8','青島市','3');
insert into `address` (`id`, `name`, `pid`) values('9','煙臺市','3');
insert into `address` (`id`, `name`, `pid`) values('10','金水區','4');
insert into `address` (`id`, `name`, `pid`) values('11','中原區','4');
insert into `address` (`id`, `name`, `pid`) values('12','鼓樓區','5');
insert into `address` (`id`, `name`, `pid`) values('13','祥符區','5');
insert into `address` (`id`, `name`, `pid`) values('14','長安區','6');
insert into `address` (`id`, `name`, `pid`) values('15','蓮湖區','6');
insert into `address` (`id`, `name`, `pid`) values('16','寶塔區','7');
insert into `address` (`id`, `name`, `pid`) values('17','安塞區','7');
insert into `address` (`id`, `name`, `pid`) values('18','嶗山區','8');
insert into `address` (`id`, `name`, `pid`) values('19','李滄區','8');
insert into `address` (`id`, `name`, `pid`) values('20','天橋區','9');
insert into `address` (`id`, `name`, `pid`) values('21','長清區','9');
新增後資料展示如下
查詢語句
//現根據id查到區
SELECT NAME FROM address WHERE id=21;
//查詢到的區之後再根據他後面的pid去查詢市
SELECT NAME FROM address WHERE id=(SELECT pid FROM address WHERE id=21);
//查詢到的市之後再根據他後面的pid去查詢省
SELECT NAME FROM address WHERE id=(SELECT pid FROM address WHERE id=(SELECT pid FROM address WHERE id=21));