如何在 MariaDB 中将对象转换为 JSON_TABLE?

How to convert an object into a JSON_TABLE in MariaDB?

我有一个 products table,其中包含一个 JSONproduct_logs。在此内部,它包含类似于以下内容的内容:

{
  "c8eebc99-d936-3245-bc8d-17694f4ecb58": {
    "created_at": "2022-05-08T15:33:33.591166Z",
    "event": "product-created",
    "user": null
  },
  "ce7b171b-b479-332f-bf9e-54b948581179": {
    "created_at": "2022-05-08T15:33:33.591174Z",
    "event": "near-sell-by",
    "user": null
  }
}

我只想 return 行在 product_logs 中有 near-sell-by 事件的产品,所以我尝试这样做:

SELECT 
    products.*
FROM products,
     JSON_TABLE(product_logs, '$[*]', COLUMNS (
         created_at DATETIME PATH '$.created_at',
         event VARCHAR(MAX) PATH '$.event'
     ) logs
WHERE
    logs.event = 'near-sell-by'

但是,我似乎遇到了以下错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(product_logs, '$[*]', COLUMNS ( created_at DATETIME PATH '$.cr...' at line 4

任何对我出错的地方的帮助将不胜感激

你好像是从别的数据库里抄来的,mysql里面没有varchar8max),语法有点复杂,需要好好理解json

像workbench这样的gui,起码能帮你识别错误,但帮不了你

CREATE TABLE products (product_logs varchar(1209))
INSERT INTO products VALUES ('{
  "c8eebc99-d936-3245-bc8d-17694f4ecb58": {
    "created_at": "2022-05-08T15:33:33.591166Z",
    "event": "product-created",
    "user": null
  },
  "ce7b171b-b479-332f-bf9e-54b948581179": {
    "created_at": "2022-05-08T15:33:33.591174Z",
    "event": "near-sell-by",
    "user": null
  }
}
')
SELECT 
    products.*,logs.created_at,logs.event
FROM products,
     JSON_TABLE(products.product_logs, '$.*'
     COLUMNS (
         created_at DATETIME PATH '$.created_at',
         event Text PATH '$.event'
     )) logs
WHERE
    logs.event = 'near-sell-by'
product_logs                                                                                                                                                                                                                                                                                                                               | created_at          | event       
:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ | :-----------
{<br>  "c8eebc99-d936-3245-bc8d-17694f4ecb58": {<br>    "created_at": "2022-05-08T15:33:33.591166Z",<br>    "event": "product-created",<br>    "user": null<br>  },<br>  "ce7b171b-b479-332f-bf9e-54b948581179": {<br>    "created_at": "2022-05-08T15:33:33.591174Z",<br>    "event": "near-sell-by",<br>    "user": null<br>  }<br>}<br> | 2022-05-08 15:33:34 | near-sell-by

db<>fiddle here