将 mysql 中的 JSON 数组列查询到行中
query JSON array column in mysql into rows
我有一个 table 数据像
| user_id | favorite_foods |
|--------- |-------------------------------------- |
| user1 | ["milk","cake"] |
| user2 | null |
| user3 | ["cake","hotdogs"] |
| user4 | ["cheese","apples","cake","hotdogs"] |
我想将数组中的数据提取为更规范化的形式,例如
| user1 | milk |
| user1 | cake |
| user2 | null |
| user3 | cake |
| user3 | hotdogs |
| user4 | cheese |
| user4 | apples |
| user4 | cake |
| user4 | hotdogs |
似乎如果这是可能的,它会与 JSON_EXTRACT
但我没有看到任何关于是否可以为每个路径表达式结果输出一行的文档,这样其他非 JSON列在路径结果旁边输出。
select user_id, j.food from ihaveatablewithdatalike
cross join json_table(favorite_foods, '$[*]' columns (
food varchar(20) path '$')) as j;
+---------+---------+
| user_id | food |
+---------+---------+
| user1 | milk |
| user1 | cake |
| user3 | cake |
| user3 | hotdogs |
| user4 | cheese |
| user4 | apples |
| user4 | cake |
| user4 | hotdogs |
+---------+---------+
我有一个 table 数据像
| user_id | favorite_foods |
|--------- |-------------------------------------- |
| user1 | ["milk","cake"] |
| user2 | null |
| user3 | ["cake","hotdogs"] |
| user4 | ["cheese","apples","cake","hotdogs"] |
我想将数组中的数据提取为更规范化的形式,例如
| user1 | milk |
| user1 | cake |
| user2 | null |
| user3 | cake |
| user3 | hotdogs |
| user4 | cheese |
| user4 | apples |
| user4 | cake |
| user4 | hotdogs |
似乎如果这是可能的,它会与 JSON_EXTRACT
但我没有看到任何关于是否可以为每个路径表达式结果输出一行的文档,这样其他非 JSON列在路径结果旁边输出。
select user_id, j.food from ihaveatablewithdatalike
cross join json_table(favorite_foods, '$[*]' columns (
food varchar(20) path '$')) as j;
+---------+---------+
| user_id | food |
+---------+---------+
| user1 | milk |
| user1 | cake |
| user3 | cake |
| user3 | hotdogs |
| user4 | cheese |
| user4 | apples |
| user4 | cake |
| user4 | hotdogs |
+---------+---------+