[英]How to extract different json elements from the same table in SQL query?
I am querying from a table with the following format:我正在从具有以下格式的表中查询:
id|provider|score
--------------------------------
1 | att | '{"attscore":300}'
1 | verizon | '{"verizonscore":299}'
2 | att | '{"attscore":200}'
3 | verizon | '{"verizonscore":155}'
I am trying to get a table that looks like the following:我正在尝试获取如下所示的表格:
id|attscore|verizonscore
-------------------------
1 | 300 | 299
2 | 200 | null
3 | null | 155
Note that used to json in sql注意在 sql 中使用了 json
CREATE TABLE table1 ( `id` INTEGER, `provider` VARCHAR(7), `score` VARCHAR(22) ); INSERT INTO table1 (`id`, `provider`, `score`) VALUES ('1', 'att', '{"attscore":300}'), ('1', 'verizon', '{"verizonscore":299}'), ('2', 'att', '{"attscore":200}'), ('3', 'verizon', '{"verizonscore":155}');
SELECT id, GROUP_CONCAT(CASE WHEN provider = 'att' THEN `score`->"$.attscore" ELSe NULL END) attscore,GROUP_CONCAT(CASE WHEN provider = 'verizon' THEN `score`->"$.verizonscore" ELSe NULL END) verizonscore FROM table1 GROUP BY id
id |编号 | attscore |
攻击力 | verizonscore -: |:------- |:----------- 1 |
verizoncore -: |:------- |:------------ 1 | 300 |
300 | 299 2 |
299 2 | 200 |
200 | null 3 |
null 3 | null |
null | 155
155
This works with a fixed number of column quite well, if you have much more of these you need to do something like this这适用于固定数量的列,如果你有更多这些,你需要做这样的事情
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.