How to search JSON array in MySQL?

后端 未结 8 897
生来不讨喜
生来不讨喜 2020-11-29 06:03

Let\'s say I have a JSON column named data in some MySQL table, and this column is a single array. So, for example, data may contain:

8条回答
  •  眼角桃花
    2020-11-29 06:05

    Since MySQL 8 there is a new function called JSON_TABLE.

    CREATE TABLE my_table (id INT, data JSON);
    
    INSERT INTO my_table VALUES 
      (1, "[1,2,3,4,5]"), 
      (2, "[0,1,2]"), 
      (3, "[3,4,-10]"), 
      (4, "[-1,-2,0]");
    
    SELECT DISTINCT my_table.* 
    FROM my_table, JSON_TABLE(data, "$[*]" COLUMNS(nr INT PATH '$')) as ids 
    WHERE ids.nr > 2;
    
    +------+-----------------+
    | id   | data            |
    +------+-----------------+
    |    1 | [1, 2, 3, 4, 5] |
    |    3 | [3, 4, -10]     |
    +------+-----------------+
    2 rows in set (0.00 sec)
    

提交回复
热议问题