[英]how to select a part of a text column as new column in mysql query
I have a text column that save a json string on it.我有一个文本列,其中保存了 json 字符串。 I want to select specific element of json as new column and i do not want to change type of this column to json.
我想将 json 的 select 特定元素作为新列,并且我不想将此列的类型更改为 json。 Is it possible?
可能吗? How can i do that?
我怎样才能做到这一点?
My table name is 'logs' and my column name is 'response' and my target element in JSON string is 'server_response_time'.我的表名是“logs”,列名是“response”,JSON 字符串中的目标元素是“server_response_time”。
If you have a valid JSON string stored in a string column, you can directly use JSON functions on it.如果您在字符串列中存储了有效的 JSON 字符串,则可以直接在其上使用 JSON 函数。 MySQL will happily convert it to JSON under the hood.
MySQL 会在引擎盖下愉快地将其转换为 JSON。
So:所以:
with t as (select '{"foo": "bar", "baz": "zoo"}' col)
select col, col ->> '$.foo' as foo
from t
If your string is not valid JSON, this generates a runtime error.如果您的字符串不是有效的 JSON,则会产生运行时错误。 This is one of the reasons why I would still recommend storing your data as
JSON
rather than string: that way, data integrity is enforced at the time when your data is stored, rather than delayed until it is read.这就是为什么我仍然建议将您的数据存储为
JSON
而不是字符串的原因之一:这样,在存储数据时强制执行数据完整性,而不是延迟到读取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.