在MySQL中,可以使用JSON_CONTAINS函數來搜索JSON數組中的元素。這里有一個簡單的例子:
假設有一個名為items的表,其中有一個名為attributes的列,包含JSON數組。
CREATE TABLE items (id INT AUTO_INCREMENT PRIMARY KEY,attributes JSON
);INSERT INTO items (attributes) VALUES
('["apple", "banana", "cherry"]'),
('["banana", "cherry", "date"]'),
('["apple", "banana", "date"]');
如果你想要搜索包含"banana"的attributes,可以使用以下查詢:
SELECT * FROM items
WHERE JSON_CONTAINS(attributes, JSON_OBJECT('key', 'banana'));
JSON數組
INSERT INTO items (attributes) VALUES
('[1, 2, 3]'),
('[1, 104, 101]'),
('[102, 101, 202]');
如果要查詢包含 101 這個數字的 attributes
SELECT * FROM `items`
WHERE JSON_CONTAINS(`attributes`, CAST(101 AS JSON))