2017-06-29 78 views
3

我已經有了對象的JSON列表一樣,MySQL的json_search

[{ 
    "something": "bla", 
    "id": 2 
}, { 
    "something": "yes", 
    "id": 1 
}] 

id領域始終是一個數值。但是,當我試圖找到id = 2,則MySQL返回NULL

select 
    json_search(
     json_extract(
      '[{"something": "bla" ,"id": 2}, {"something": "yes","id": 1}]', 
      "$[*].id" 
     ), 
     'one', 
     2 
    ) as json_search; 

json_search | 
------------| 
      | 

當我在我的JSON id對象,而不是一個數值,使用一個字符串作爲值,我得到了與指數0

select 
    json_search(
     json_extract(
      '[{"something": "bla" ,"id": "2"}, {"something": "yes","id": 1}]', 
      "$[*].id" 
     ), 
     'one', 
     "2" 
    ) as json_search; 

json_search | 
------------| 
"$[0]"  | 
結果

我使用的是MySQL 5.7.17

@@version | 
-----------| 
5.7.17-log | 

是JSON陣列數字搜索不是MySQL提供的?

回答

0

雖然JSON_EXTRACT函數返回[2, 1],這是一個有效的JSON,如果你搜索documentationJSON_SEARCH功能是:

JSON_SEARCH(json_doc,one_or_all,SEARCH_STR [,的escape_char [,路徑] .. 。])

所以,據我所知,你只能使用STRING值,而不是數值。但是,對於您的問題的一種解決方案可能是使用JSON_CONTAINS函數,因爲如果數值存在或不存在,它將返回1或0。

select 
    json_contains(
     json_extract(
      '[{"something": "bla" ,"id": 2}, {"something": "yes","id": 1}]', 
      "$[*].id" 
     ), 
     "2" 
    ) as json_contains; 

唯一的問題是,您無法獲取JSON文檔中給定值的路徑。希望它有幫助。

+0

但後來我不得不使用字符串值作爲搜索值...還算不上令人滿意 – Markus

0

你可以嘗試一些複雜的,不直觀,並可能有性能問題,但它是一個選項:

mysql> SELECT JSON_SEARCH(
    -> REPLACE(
    ->  REPLACE(
    ->  REPLACE(
    ->   JSON_EXTRACT('[ 
    '>       {"something": "bla" ,"id": 2}, 
    '>       {"something": "yes","id": 1} 
    '>      ]', "$[*].id"), 
    ->  ', ', '","'), 
    ->  '[', '["'), 
    -> ']', '"]'), 
    -> 'one', '2') `json_search`; 
+-------------+ 
| json_search | 
+-------------+ 
| "$[0]"  | 
+-------------+ 
1 row in set (0.00 sec) 
+0

好, 這樣可行。但事實上,它看起來並不直觀,我擔心實際數據會變慢。 – Markus