从 json 列获取所有键并转换为行

get all keys from json column and convert to rows

我有一个如下所示的 table,其中 cities 是 JSON

ID cities
1 ["madrid"]
2 ["london", "madrid", "paris"]
3 ["london", "paris"]
4 ["london"]
5 ["rome", "berlin"]

我想将该列转换为行,其中所有单个城市都有自己的行

city
madrid
london
paris
rome
berlin

我试过

SELECT distinct JSON_VALUE(JSON_EXTRACT(cities, '$[*]'), '$[*]') as cities FROM table_cities

但我得到了这个

city
madrid
NULL
london
  1. 如果您使用的是 MySQL 8.0 版,您可以尝试使用函数 JSON_TABLE(已在 dbfiddle 上测试)
SELECT DISTINCT tmp.city
FROM table_cities c,
JSON_TABLE(
  c.cities,
  '$[*]'
  COLUMNS(
  city VARCHAR(10) PATH '$[0]'
  )
) tmp;
  1. 对于 MariaDB 10.4.2,您可以试试这个。 (在 dbfiddle 上测试)
CREATE TABLE main_table (
    cities VARCHAR(1000)
);

-- create procedure
CREATE PROCEDURE proc1()
BEGIN
SET @index := 0;
SELECT @json_length := MAX(JSON_LENGTH(cities))
FROM table_cities;

REPEAT
   INSERT INTO main_table (cities)
   SELECT JSON_EXTRACT(cities,CONCAT("$[",@index,"]")) FROM table_cities;
   SET @index = @index + 1;
UNTIL @index = @json_length 
END REPEAT;
END;

-- call procedure
CALL proc1;

-- query result
SELECT DISTINCT REPLACE(cities, '"', '') AS city 
FROM main_table
WHERE cities IS NOT NULL;