在列中分解mysql字符串

wtlkbnrh  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(345)

我有一个mysql数据库,想在特定列中搜索特定数据。

{"pump":"0","track":"0","bats":"1","acc":"1","batl":"6","gpslev":"5"}

这是我想在bats为0时提取的列中的信息,然后使用php字符串和echo在我的php屏幕上显示它。
我读过 SUBSTRING_INDEX 但是当我用它的时候,它会把所有的东西都显示在 bat 的左边。我需要一个搜索字符串,可以搜索 bat 和 WHERE bats=0 如有任何帮助,我们将不胜感激。

kuhbmx9i

kuhbmx9i1#

mysql> create table json_test(c json);
Query OK, 0 rows affected (0.40 sec)

mysql> insert into json_test values('{"pump":"0","track":"0","bats":"1","acc":"1","batl":"6","gpslev":"5"}');
Query OK, 1 row affected (0.15 sec)

mysql> select * from json_test;
+----------------------------------------------------------------------------------+
| c                                                                                |
+----------------------------------------------------------------------------------+
| {"acc": "1", "batl": "6", "bats": "1", "pump": "0", "track": "0", "gpslev": "5"} |
+----------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select json_extract(c,'$.bats') from json_test;
+--------------------------+
| json_extract(c,'$.bats') |
+--------------------------+
| "1"                      |
+--------------------------+
1 row in set (0.00 sec)

mysql> select json_extract(c,'$.bats') from json_test where json_extract(c,'$.bats') = "1";
+--------------------------+
| json_extract(c,'$.bats') |
+--------------------------+
| "1"                      |
+--------------------------+
1 row in set (0.00 sec)
dohp0rv5

dohp0rv52#

如果您的mysql版本支持json,那么请尝试下面的查询。

SELECT JSON_EXTRACT(json_data, '$.bats') FROM `json_test` WHERE JSON_SEARCH(json_data, 'bats', '0%')
zengzsys

zengzsys3#

使用json函数:

SELECT col->"$.bats"    -- and maybe other columns you want here
FROM yourTable
WHERE col->"$.bats" = '0';

演示

编辑:
如果您的mysql版本不支持json函数,我们仍然可以尝试使用 REGEXP :

SELECT *
FROM yourTable
WHERE col REGEXP '"bats":"0"';

相关问题