我有两张table
CREATE TABLE json_data_table(d_id int, d1_json json, d2_json json);
CREATE TABLE user_data(uid int, username varchar);
数据分别为
INSERT INTO user_data VALUES
(1,'test_user_1'),
(2,'test_user_2'),
(3,'test_user_3');
INSERT INTO json_data_table VALUES
(1,'{"stage1":1,"stage2":2 }', '{
"stage1": {
"date": "12-01-2023",
"status": "open",
"uid": "2"
},
"stage2": {
"date": "22-01-2023",
"status": "close",
"uid": "1"
}
}'),
(2,'{"stage1":11,"stage2":21 }', '{
"stage1": {
"date": "21-2-2023",
"status": "open",
"uid": "3"
},
"stage2": {
"date": "2-2-2023",
"status": "close",
"uid": "2"
}
}');
现在,我要将user_data
表与json_data_table
和uid
连接起来,以获得username
预期表格输出:
我通过简单地获取json->>key_name
来获得其他列,这里是select
查询。
SELECT d1_json->>'stage1' as stage1,
d1_json->>'stage2' as stage2,
d2_json->'stage1'->>'date' as s1_date,
d2_json->'stage1'->>'status' as s1_status,
d2_json->'stage1'->>'uid' as s1_uid,
d2_json->'stage2'->>'date' as s2_date,
d2_json->'stage2'->>'status' as s2_status,
d2_json->'stage2'->>'uid' as s2_uid
FROM json_data_table AS jd;
如何连接表以获得如图所示的预期表?
2条答案
按热度按时间3ks5zfa01#
试试这个:
pxq42qpu2#
您只需连接它并使用表达式提取连接条件中的
uid
。由于需要不同的user_data
集合,因此需要连接表两次。最后,由于uid
是数字,而JSON由文本组成,因此必须在两者之间进行转换。我选择在JSON端进行转换。因为这使得能够使用user_data
的索引,这在真实的使用情况中似乎是合理的。DB-Fiddle to play with .