Angularjs: Country, state, city select from from database

后端 未结 1 1731
醉梦人生
醉梦人生 2021-01-28 22:32

I want have country, state and city selection on my website. I have country, state, city tables in database.

city table

CREATE TABLE IF NOT EXISTS `citie         


        
1条回答
  •  青春惊慌失措
    2021-01-28 23:02

    Considering the following data set...

    DROP TABLE IF EXISTS cities;
    
    CREATE TABLE `cities` (
       `city_id` int(11) NOT NULL,
       `city_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
       `state_id` int(11) NOT NULL,
       `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active'
    ) ENGINE=InnoDB AUTO_INCREMENT=6178 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    DROP TABLE IF EXISTS countries;
    
    CREATE TABLE `countries` (
       `country_id` int(11) NOT NULL,
       `country_name` varchar(30) CHARACTER SET utf8 NOT NULL,
       `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active'
     ) ENGINE=InnoDB AUTO_INCREMENT=240 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    DROP TABLE IF EXISTS states;
    
    CREATE TABLE `states` (
       `state_id` int(11) NOT NULL,
       `state_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
       `country_id` int(11) NOT NULL,
       `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active'
    ) ENGINE=InnoDB AUTO_INCREMENT=1652 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    INSERT INTO cities VALUES
     (1,'San Francisco',1,1),
     (2,'Los Angeles',1,1),
     (3,'Winnipeg',2,1),
     (4,'Toronto',3,1);
    
    INSERT INTO states VALUES
     (1,'California',1,1),
     (2,'Manitoba',2,1),
     (3,'Ontario',2,1);
    
    INSERT INTO countries VALUES
     (1,'USA',1),
     (2,'Canada',1);
    
    SELECT x.country_id
         , x.country_name
         , y.state_id
         , y.state_name
         , z.city_id
         , z.city_name 
      FROM countries x 
      JOIN states y 
        ON y.country_id = x.country_id 
      JOIN cities z 
        ON z.state_id = y.state_id;
    +------------+--------------+----------+------------+---------+---------------+
    | country_id | country_name | state_id | state_name | city_id | city_name     |
    +------------+--------------+----------+------------+---------+---------------+
    |          1 | USA          |        1 | California |       1 | San Francisco |
    |          1 | USA          |        1 | California |       2 | Los Angeles   |
    |          2 | Canada       |        2 | Manitoba   |       3 | Winnipeg      |
    |          2 | Canada       |        3 | Ontario    |       4 | Toronto       |
    +------------+--------------+----------+------------+---------+---------------+
    

    The following code will output the desired result...

    
    

    This outputs...

    {"USA":{"California":["San Francisco","Los Angeles"]},"Canada":{"Manitoba":["Winnipeg"],"Ontario":["Toronto"]}}
    

    0 讨论(0)
提交回复
热议问题