Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

sql - Filter records using JSON function for JSON array

There is one table where data stored in JSON format. I need to find how many records are there where Quote Required.

JSON

[{"id":14,"desc":"Job is incomplete.","quote_required":"Yes"}, 
 {"id":14,"desc":"appointment need to rebook","quote_required":"Yes","start-date":"2021-11-20"}]

I am trying to achieve about using below JSON_CONTAINS() and JSON_EXTRACT()

SELECT COUNT(*)   
  FROM `products`   
 WHERE JSON_CONTAINS( JSON_EXTRACT(submit_report, "$.quote_required"), '"Yes"' )

But I am getting 0 results here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can search for each element of the array whether having quote_required equals to Yes through use of index values starting from 0 upto length of the array minus 1 by generating index values with recursive common table expression such as

WITH recursive cte AS 
(
  SELECT 0 AS n
  UNION ALL
  SELECT n + 1 AS value
    FROM cte
   WHERE cte.n < ( SELECT JSON_LENGTH(submit_report) - 1 FROM `products` ) 
)
SELECT SUM(JSON_CONTAINS(JSON_EXTRACT(submit_report, CONCAT("$[",n,"].quote_required")),
                                      '"Yes"')) AS count
  FROM cte
  JOIN `products`

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...