How to get values from MySQL(5.6) column if that contains json document as string

前端 未结 10 714
萌比男神i
萌比男神i 2020-12-02 18:48

How to get values from MySQL(5.6) column if that contains JSON document as a string

For example, if we have a table - employee in that we have three columns id, nam

10条回答
  •  没有蜡笔的小新
    2020-12-02 19:23

    Yes , you can definitely to it using JSON_EXTRACT() function in mysql.

    lets take a table that contains JSON (table client_services here) :

    +-----+-----------+--------------------------------------+
    | id  | client_id | service_values                       |
    +-----+-----------+------------+-------------------------+
    | 100 |      1000 | { "quota": 1,"data_transfer":160000} |
    | 101 |      1000 | { "quota": 2,"data_transfer":800000} |
    | 102 |      1000 | { "quota": 3,"data_transfer":70000}  |
    | 103 |      1001 | { "quota": 1,"data_transfer":97000}  |
    | 104 |      1001 | { "quota": 2,"data_transfer":1760}   |
    | 105 |      1002 | { "quota": 2,"data_transfer":1060}   |
    +-----+-----------+--------------------------------------+
    

    To Select each JSON fields , run this query :

    SELECT 
        id, client_id, 
        json_extract(service_values, '$.quota') AS quota,
        json_extract(service_values, '$.data_transfer') AS data_transfer
    FROM client_services;
    

    So the output will be :

    +-----+-----------+----------------------+
    | id  | client_id | quota | data_transfer|
    +-----+-----------+----------------------+
    | 100 |      1000 |     1 |       160000 |
    | 101 |      1000 |     2 |       800000 |
    | 102 |      1000 |     3 |        70000 |
    | 103 |      1001 |     1 |        97000 |
    | 104 |      1001 |     2 |         1760 |
    | 105 |      1002 |     2 |         1060 |
    +-----+-----------+----------------------+
    

    Hope this solves your problem!

提交回复
热议问题