简体   繁体   中英

json_table Incorrect agguments

I have a table like the following structure:

| id |         data         |
|  1 | {"products":[1,2,3]} |
|  2 | {"products":[2,5,7]} |
|  3 | {"products":[2,4,1]} |
|  4 | {"products":[7,8]}   |
|  5 | {"products":[2,8]}   |

I want to join this table to a query, and use the ids in the product JSON to join a 3. table. The 3. table called products.

I managed to write the query but I got this message all the time:

Error Code: 1210. Incorrect arguments to JSON_TABLE

Unfortunately I can't change the structure, and I must get these Ids from the JSON field.

I have the following query so far:

select pd.`id` pd.parameter_condition->>'$.products' as `product_id`
from `shop`.`ordering` o  
inner join `shop`.`ordered_product` op on (op.`order_id` = o.`id`)   
-- [... a lot more joins] 
inner join `shop`.`price_dependency` pd on (pd.`attribute_value_id` = av.`id`) 
where o.type_id = 4

Which gives back the following result:

| id |    product_id`   |
|  2 |["25"]            |
|  3 |["10", "12"]      |
|  5 |["10", "15", "22"]|

But what I want in the end is something like this:

| id | product_id` |
|  2 |      25     |
|  3 |      10     |
|  3 |      12     |
|  5 |      10     |
|  5 |      15     |
|  5 |      22     |

You can try to use JSON_EXTRACT to get JSON array value.

Create a result set for your index of JSON array continue as needed to max length of JSON array.

then use T CROSS JOIN the index table, to use JSON_EXTRACT function to only show the value, which index exists in the array.

Schema (MySQL v8.0)

CREATE TABLE T(
  id int,
  product_id varchar(50)
);
insert into T values (2,'["25"]');
insert into T values (3,'["10", "12"]');
insert into T values (5,'["10", "15", "22"]');

Query #1

SELECT
  id,
  JSON_EXTRACT(product_id, concat('$[',idx,']')) product_id
FROM T
 CROSS JOIN ( 
  SELECT 0 AS idx UNION
  SELECT 1 AS idx UNION
  SELECT 2 AS idx 
  ) AS indexes 
where  JSON_EXTRACT(product_id, concat('$[',idx,']')) is not null
order by id;

| id  | product_id |
| --- | ---------- |
| 2   | "25"       |
| 3   | "10"       |
| 3   | "12"       |
| 5   | "10"       |
| 5   | "15"       |
| 5   | "22"       |

View on DB Fiddle

NOTE

T means your current result set.

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