我有一个奇怪的问题:表格中的JSON列中有一个价格,以下语句给出了不同的结果,而它们应该给出相同的内容:
CAST(COALESCE(JSON_EXTRACT(item.price_details, "$.shipping.price"), 0) AS FLOAT) AS shippricecoalfloat
COALESCE(CAST(JSON_EXTRACT(item.price_details, "$.shipping.price") AS FLOAT), 0) AS shippricefloatcoal
要检查我还添加了 json_extract(item.price_details,'' 。
。
>
I have a strange problem: There is a price in a JSON column in a table and the following statements give different results while they should give the same thing:
CAST(COALESCE(JSON_EXTRACT(item.price_details, "$.shipping.price"), 0) AS FLOAT) AS shippricecoalfloat
COALESCE(CAST(JSON_EXTRACT(item.price_details, "$.shipping.price") AS FLOAT), 0) AS shippricefloatcoal
Just to check I also added a JSON_EXTRACT(item.price_details, "$.shipping.price") AS shipprice
Result:

MariaDB version: mariadb Ver 15.1 Distrib 10.3.31-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
DB Fiddle (I couldn't use the same MariaDB version but it behaves the same anyways apparently)
发布评论
评论(2)
您正在使用错误的JSON功能。
JSON_EXTRACT()
返回该路径上找到的JSON对象。这就是为什么在您的小提琴中,您仍然会看到双引号。您想从特定路径返回标量值。因此,使用
JSON_VALUE()
另外,与Datatypes的“混乱”的一部分是由您的JSON引起的,将某些值存储为带有双引号的字符串,而有些则作为数字值。我强烈建议不要将数字值封闭在JSON中的双引号中。
You're using the wrong JSON function.
JSON_EXTRACT()
returns a JSON Object found at that path. That's why in your fiddle you still see double quotes.You want to return a scalar value from a specific path. So, use
JSON_VALUE()
Also, part of the "mess" with datatypes is caused by your JSON storing some values as strings with double quotes, and some as numeric values. I strongly recommend not enclosing numeric values in double quotes in your JSON.
https://dbfiddle.uk/?rdbms=mariadb_10.6&fiddle=d67fa297a5cc4248a06750d71581c022
我相信这是您的问题的“解决方案”:
我将尝试解释我如何看待它...
首先要知道的是:“ coalesce()具有与参数相同的数据类型。”
此
cocce(json_extract(Price_details,“ $ .shipping.price”),0)作为煤炭
返回返回“ 0.8648”,但作为字符串(varchar),因此它返回'0.8648“ 0.8648”''''''''this
> cast(json_extract(price_details,“ $ .shipp.price”)作为caast
返回0.8648,因此没有问题...此
选择cast('0.8648“ as float)返回0与您的结果相同的0 ...
您无法将其带有双引号的值施放为浮点。
当您合并浮子值时,您将获得结果,而0等于该浮点值。
我相信这解释了吗?
” “ 098”与此'098'相同?
I believe this is "the solution" for your question:
I will try to explain how I see it...
First thing to know is: "COALESCE() has the same data type as the argument."
This
COALESCE(JSON_EXTRACT(price_details, "$.shipping.price"), 0) as coal
returns "0.8648" but as a string(varchar) so it returns '"0.8648"'This
CAST(JSON_EXTRACT(price_details, "$.shipping.price") AS FLOAT) as caast
returns 0.8648 so no problems there...This
select cast('"0.8648"' as float)
returns 0 which is the same as your result...You can not cast a value with double quotes in it to a float.
You will get a result when you coalesce float value and 0 equal to that float value.
I believe this explains it ?
DEMO
Maybe as addition to this I should ask/say isn't this "098" same as this '098' ?