Extract data from json inside mysql field

前端 未结 5 1353
无人共我
无人共我 2021-01-04 20:47

I\'ve got a a table with rows, and one of the rows has a field with data like this

{\"name\":\"Richard\",\"lastname\":null,\"city\":\"Olavarria\",\"cityId\":         


        
5条回答
  •  温柔的废话
    2021-01-04 21:16

    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 |
    +-----+-----------+----------------------+
    

    NOW, if you want lets say DISTINCT quota , then run this query :

    SELECT 
       distinct( JSON_EXTRACT(service_values, '$.quota')) AS quota
    FROM client_services;
    

    So this will result into your desired output :

    +-------+
    | quota |
    +-------+
    |     1 |
    |     2 |
    |     3 |
    +-------+
    

    hope this helps!

提交回复
热议问题