2 回答

TA貢獻1801條經驗 獲得超8個贊
您只需使用json_contains()
:
select *
from mytable
where json_contains(data_column, '{ "barcode": "foo" }' , '$.placards')
此短語為:搜索路徑 'placards' 下數組中包含候選對象的鍵/值對的任何元素'{ "barcode": "foo" }',其中 'foo' 是您搜索的條形碼值。
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)) );

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 還需要更多空間來存儲相同的數據。
- 2 回答
- 0 關注
- 174 瀏覽
添加回答
舉報