亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

針對嵌套 JSON 字段、MYSQL、PHP 的查詢

針對嵌套 JSON 字段、MYSQL、PHP 的查詢

PHP
楊__羊羊 2023-12-15 15:47:59
我有這樣的結構:{"placards":    [    {"barcode": "string", "destination":"string", "weight":"string"},    {etc...}]}存儲在 MYSQL 數據庫中的單個列上。我正在嘗試搜索特定的條形碼,并返回該條形碼位于該行的 json 結構內的整行。我嘗試了兩種方法,兩種方法都在堆棧溢出中找到,但我沒有在一種方法中得到結果,下面我將發布后者的錯誤。attempt1:"SELECT * FROM table WHERE placards[*->barcode] = ".$job->events[0]->imcb;attempt2:    $sampleBC = $job->events[0]->imcb;        $sql = 'SELECT * FROM(        SELECT data_column->"[*]" as row        from table        where $sampleBC IN JSON_EXTRACT(data_column, ""    )    WHERE row->".barcode" = $sampleBC';這些方法都不會在 $stmt->error 上給出錯誤,但我實際上無法通過此查詢成功獲取任何內容。
查看完整描述

2 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

您只需使用json_contains()

select *

from mytable

where json_contains(data_column, '{ "barcode": "foo" }' , '$.placards')

此短語為:搜索路徑 'placards' 下數組中包含候選對象的鍵/值對的任何元素'{ "barcode": "foo" }',其中 'foo' 是您搜索的條形碼值。

DB Fiddle 演示

set @data_column =?

? ? '{

? ? ? ? "placards": [

? ? ? ? ? ? {"barcode": "foo", "destination":"string", "weight":"string"},

? ? ? ? ? ? {"barcode": "bar", "destination":"string", "weight":"string"}

? ? ? ? ]

? ? }';


select json_contains(@data_column, '{ "barcode": "foo" }' , '$.placards') is_a_match;

| is_a_match |

| ---------: |

|? ? ? ? ? 1 |


select json_contains(@data_column, '{ "barcode": "baz" }' , '$.placards') is_a_match;


| is_a_match |

| ---------: |

|? ? ? ? ? 0 |

從 MySQL 8.0.17 開始,你甚至可以在嵌套的 json 數組上創建多值索引,這樣數據庫就不需要為此查詢執行全表掃描:


alter table mytable?

? ? add index myidx( (cast(data_column -> '$.placards' as unsigned array)) );


查看完整回答
反對 回復 2023-12-15
?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

您必須使用 JSON_TABLE():


SELECT mytable.* FROM mytable,

  JSON_TABLE(mytable.data_column, '$.placards[*]' COLUMNS (

    barcode VARCHAR(100) PATH '$.barcode',

    destination VARCHAR(100) PATH '$.destination', 

    weight VARCHAR(20) PATH '$.weight'

  )) AS j

WHERE j.barcode = ?

如果將這些字段存儲在普通列中而不是 JSON 中,則會簡單得多。每個標語牌存儲一行,并包含 barcode、description 和 weight 的單獨列。


SELECT m.* FROM mytable AS m JOIN placards AS p ON m.id = p.mytableid 

WHERE p.barcode = ?

我在 Stack Overflow 問題中看到的 MySQL 中 JSON 的大多數使用都是不必要的,因為數據不需要 JSON 的靈活性。針對 JSON 文檔的查詢很難編寫,也很難優化。 JSON 還需要更多空間來存儲相同的數據。


查看完整回答
反對 回復 2023-12-15
  • 2 回答
  • 0 關注
  • 174 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號