我试图了解Sqlite JSON扩展的工作方式。可以说一家公司有几个分支机构,每个分支机构都有一个库存目录,因此我创建了一个表:-
SQL = "CREATE TABLE BranchStock (branch VARCHAR, stock JSON)"
....
然后我插入一些项目,例如:-
SQL = "INSERT INTO BranchStock (branch, stock) values('Melbourne', json_array(json_object('catnumber', 'ABC123', 'instock',2), json_object('catnumber', 'BCD321', 'instock',5)))"
....
SQL = "INSERT INTO BranchStock (branch, stock) values('Sydney', json_array(json_object('catnumber', 'ABC123', 'instock',5), json_object('catnumber', 'XYZ567', 'instock',3)))"
....
现在,我正在寻找搜索SQL以列出哪些分支具有catnumber ='ABC123'和库存数量。也许是这样的:-
SQL = "SELECT branch, json_extract(stock, '$[].instock') FROM BranchStock WHERE json_valid(stock) AND json_extract(stock, '$[].catnumber') = 'ABC123'
有人可以为我提供正确的SELECT语法吗?
预先感谢
答案 0 :(得分:0)
注意:我不建议将它实际用于经常运行或在大型表上运行的任何东西,但是如果您绝对必须...
给出以下测试表:
CREATE TABLE BranchStock(branch TEXT, stock TEXT);
INSERT INTO BranchStock VALUES('Melbourne','[{"catnumber":"ABC123","instock":2},{"catnumber":"BCD321","instock":5}]');
INSERT INTO BranchStock VALUES('Sydney','[{"catnumber":"ABC123","instock":5},{"catnumber":"XYZ567","instock":3}]');
通过'ABC123'
获取商店的分支机构和库存编号:
SELECT branch, json_extract(value, '$.instock') AS instock
FROM BranchStock JOIN json_each(stock)
WHERE json_extract(value, '$.catnumber') = 'ABC123';
给予
branch instock
---------- ----------
Melbourne 2
Sydney 5
使用表定义之类的东西执行几乎任何事情都会容易得多,效率也更高
CREATE TABLE BranchStock(branch TEXT, catid TEXT, instock INTEGER);
而不是尝试搜索存储在列中的JSON数据。例如:
SELECT branch, instock FROM BranchStock WHERE catid = 'ABC123';
尤其是当您开始向索引中添加索引时。