sql >> Databasteknik >  >> RDS >> Mysql

Läs JSON-array i MYSQL

mysql> SET @`json` :=
    -> '[
    '>    {
    '>      "id": 1, "type": 2
    '>    },
    '>    {
    '>      "id": 2, "type": 1
    '>    }
    '> ]';
Query OK, 0 rows affected (0.00 sec)

Du kan få alla ids i en array:

mysql> SELECT JSON_EXTRACT(@`json` ,'$[*].id');
+----------------------------------+
| JSON_EXTRACT(@`json` ,'$[*].id') |
+----------------------------------+
| [1, 2]                           |
+----------------------------------+
1 row in set (0.00 sec)

Kan komma åt varje JSON ids :

mysql> SELECT JSON_EXTRACT(@`json` ,'$[0].id');
+----------------------------------+
| JSON_EXTRACT(@`json` ,'$[0].id') |
+----------------------------------+
| 1                                |
+----------------------------------+
1 row in set (0.00 sec)

Försök:

mysql> DROP PROCEDURE IF EXISTS `new_procedure`;
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //

mysql> CREATE PROCEDURE `new_procedure`(`json` JSON)
    -> BEGIN
    ->   DECLARE `json_items` BIGINT UNSIGNED DEFAULT JSON_LENGTH(`json`);
    ->   DECLARE `_index` BIGINT UNSIGNED DEFAULT 0;
    -> 
    ->   DROP TEMPORARY TABLE IF EXISTS `jsonTemporary`;
    -> 
    ->   CREATE TEMPORARY TABLE IF NOT EXISTS `jsonTemporary`
    ->     (`id` BIGINT UNSIGNED NOT NULL);
    -> 
    ->   WHILE `_index` < `json_items` DO
    ->     INSERT INTO `jsonTemporary` (`id`)
    ->     VALUES (JSON_EXTRACT(`json`, CONCAT('$[', `_index`, '].id')));
    ->     SET `_index` := `_index` + 1;
    ->   END WHILE;
    -> 
    ->   SELECT `id` FROM `jsonTemporary`;
    ->   DROP TEMPORARY TABLE IF EXISTS `jsonTemporary`;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> CALL `new_procedure`(@`json`);
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Se db-fiddle .




  1. De bästa misstagen att undvika i MySQL-replikering

  2. Fråga endast de första data från en tabell

  3. Gör inloggningen säkrare

  4. varför PG::UniqueViolation:FEL:dubblettnyckelvärde bryter mot unik begränsning?