mySql - 从表

时间:2016-11-19 02:14:41

标签: php mysql

好的,我会尽量保持清醒,但要忍受我 - 这是漫长的一周:)

我们有一个表格结构如下:

+----+----------+---------+------------------+
| id | field_id | user_id |      value       |
+----+----------+---------+------------------+
|  1 | Country  |       2 | USA              |
|  2 | Country  |       3 | USA              |
|  3 | Country  |       4 | CA               |
|  4 | Country  |       5 | MX               |
|  5 | Province |       2 | FL               |
|  6 | Province |       3 | GA               |
|  7 | Province |       4 | British Columbia |
|  8 | Province |       5 | Sonara           |
|  9 | City     |       2 | Orlando          |
| 10 | City     |       3 | Brunswick        |
| 11 | City     |       4 | Vancouver        |
| 12 | City     |       5 | Nogalas          |
+----+----------+---------+------------------+`

我们需要(希望)查询返回所有Country - State / Province - City组合,以便动态生成JSON文件。

的影响
"SELECT all Provinces and Cities WHERE Country = 'USA'"

(但当然,我们的数据库表的结构 - 遗憾的是无法改变 - 它更复杂。

共享共同" user_id"的任何值。可以安全地假设"一起去#34; (即,user_id 2有" USA" for" Country"," FL" for"省"和" Orlando" ;对于" City")。

最终结果我们试图创建一个类似于下面的json文件。

{
"USA": {
    "Florida": [
        {"City": "Orlando"},
        {"City": "Palm Beach"}
    ],
    "Georgia": [
        {"City": "Atlanta"},
        {"City": "Brunswick"}
    ]
}, 
"Canada": {
    "Alberta": [
        {"City": "Calgary"}
    ],
    "Ontario": [
        {"City": "Atlanta"},
        {"City": "Brunswick"}
    ]
}
}

1 个答案:

答案 0 :(得分:0)

使用此查询的结果和一些循环,您应该能够根据需要生成Json

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE t
    (`id` int, `field_id` varchar(8), `user_id` int, `value` varchar(16))
;

INSERT INTO t
    (`id`, `field_id`, `user_id`, `value`)
VALUES
    (1, 'Country', 2, 'USA'),
    (2, 'Country', 3, 'USA'),
    (3, 'Country', 4, 'CA'),
    (4, 'Country', 5, 'MX'),
    (5, 'Province', 2, 'FL'),
    (6, 'Province', 3, 'GA'),
    (7, 'Province', 4, 'British Columbia'),
    (8, 'Province', 5, 'Sonara'),
    (9, 'City', 2, 'Orlando'),
    (10, 'City', 3, 'Brunswick'),
    (11, 'City', 4, 'Vancouver'),
    (12, 'City', 5, 'Nogalas')
;

查询1

SELECT 
    tc.`value` as Country,  
    tp.`value` as Province,  
    tcy.`value` as City
FROM (
        SELECT `value`, user_id FROM t WHERE field_id = "Country"
    ) as tc
    LEFT JOIN (
            SELECT `value`, user_id FROM t WHERE field_id = "Province"
        ) as tp
        ON tc.user_id = tp.user_id
    LEFT JOIN (
            SELECT `value`, user_id FROM t WHERE field_id = "City"
        ) as tcy
        ON tp.user_id = tcy.user_id

<强> Results

|Country|         Province |      City |
|-------|------------------|-----------|
|   USA |               FL |   Orlando |
|   USA |               GA | Brunswick |
|    CA | British Columbia | Vancouver |
|    MX |           Sonara |   Nogalas |