查询匹配的json数组键

时间:2018-12-27 20:03:54

标签: python mysql sql

我在mysql中有一个名为column_info的json字段。这是一个示例值:

[{"id": ["132605", "132750", "132772", "132773", "133065", "133150", "133185", "133188", "133271", "133298"]}, 
 {"number": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]}, 
 {"id": ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]}
]

是否可以执行以下查询:

keys = ['id', 'number', 'id']
SELECT * FROM `column_info` WHERE JSON(??) = keys

2 个答案:

答案 0 :(得分:2)

尝试:

SELECT `column_info`
FROM
  `table`,
  (SELECT @`keys` := '["id", "number", "id"]') `init`
WHERE (
  SELECT
    JSON_ARRAYAGG(
      JSON_UNQUOTE(
        JSON_EXTRACT(
          JSON_KEYS(`der`.`keys`),
          '$[0]'
        )
      )  
    )
  FROM
    JSON_TABLE(
      `column_info`,
      '$[*]'
      COLUMNS(
        `keys` JSON PATH '$'
      )  
    ) `der`
) = CAST(@`keys` AS JSON);

请参见db-fiddle

答案 1 :(得分:0)

您正在运行哪个版本的MySQL?

如果是v8,则可以尝试JSON_CONTAINS()

https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html