简体   繁体   中英

Search JSON_ARRAY using dynamic variable

Is it possible to search a JSON_ARRAY using a variable as the index as opposed to hard coding a value in?

Here's what I mean:

SELECT
t1.*,
t1.tickets->>"$[t1.arr_pos]"
FROM
(
    SELECT
    c.id AS competition_id,
    JSON_ARRAYAGG(t.id) AS tickets,
    COUNT(t.id) AS tickets_sold,
    FLOOR(RAND()*(COUNT(t.id)-0+1)) AS arr_pos
    FROM competitions c
    JOIN tickets t ON t.competition_id = c.id
    WHERE c.end_date = '2021-01-15 15:00:00'
    AND c.tickets_sold > 0
    GROUP BY c.id
) t1

If I change t1.arr_pos to a number (0, 1, 2, etc) it obviously works but I need to search based on what is contained in arr_pos.

You can use JSON_SEARCH() function to determine the index of the searched expression( in this case, picked one of the array of id values ) for the first occurence within the array along with one as the second argument, and then extract by this value to get the desired result.

SELECT t1.*, 
       JSON_EXTRACT(t1.tickets,
                    JSON_UNQUOTE(JSON_SEARCH(t1.tickets, 'one', "123")) 
                 -- example id value is 123
       ) AS Result,
       JSON_UNQUOTE(JSON_SEARCH(tickets, 'one', "123")) AS Related_Index
  FROM
  (
   <your subquery>
  )

Demo

Couldn't get JSON_SEARCH to work but what did work was the following:

SELECT
t1.*,
JSON_EXTRACT(t1.tickets, CONCAT('$[', t1.arr_pos, ']')) AS winning_ticket
FROM
(
    SELECT
    c.id AS competition_id,
    JSON_ARRAYAGG(t.id) AS tickets,
    COUNT(t.id) AS tickets_sold,
    FLOOR(RAND()*(COUNT(t.id))) AS arr_pos
    FROM competitions c
    JOIN tickets t ON t.competition_id = c.id
    WHERE c.end_date = '2021-01-15 15:00:00'
    AND c.tickets_sold > 0
    GROUP BY c.id
) t1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM