gpt4 book ai didi

mysql json数据类型在数组内搜索值

转载 作者:行者123 更新时间:2023-11-29 18:35:06 35 4
gpt4 key购买 nike

我的 MySQL 表中有一个 json 类型的列,该列中的值是一个简单的一维数组(例如 [1,2,3,4,5])。如何使用 json_contains 函数返回 json 数组中包含值“5”的所有行?

最佳答案

尝试:

mysql> DROP TABLE IF EXISTS `tbl`;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `tbl` (
-> `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `json` JSON NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO `tbl`
-> (`json`)
-> VALUES
-> ('[1,2,3,4,5]'),
-> ('[1,2,3,4]'),
-> ('[1,2]'),
-> ('[1]'),
-> ('[1,5]');
Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> SELECT
-> `id`,
-> `json`
-> FROM
-> `tbl`
-> WHERE
-> JSON_CONTAINS(`json`, '5');
+----+-----------------+
| id | json |
+----+-----------------+
| 1 | [1, 2, 3, 4, 5] |
| 5 | [1, 5] |
+----+-----------------+
2 rows in set (0.00 sec)

参见db-fiddle .

更新

mysql> DROP TABLE IF EXISTS `tbl`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `tbl` (
-> `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `json` JSON NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO `tbl`
-> (`json`)
-> VALUES
-> ('["1","2","3","4","5"]'),
-> ('["1","2","3","4"]'),
-> ('["1","2"]'),
-> ('["1"]'),
-> ('["1","5"]');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> SELECT
-> `id`,
-> `json`
-> FROM
-> `tbl`
-> WHERE
-> JSON_CONTAINS(`json`, '"5"');
+----+---------------------------+
| id | json |
+----+---------------------------+
| 1 | ["1", "2", "3", "4", "5"] |
| 5 | ["1", "5"] |
+----+---------------------------+
2 rows in set (0.00 sec)

参见db-fiddle .

关于mysql json数据类型在数组内搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383974/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com