在查询中嵌入 JSON

问题描述 投票:0回答:1

我有一个用户表和一个注释表,我正在尝试找出最好的前进方法,以便我可以轻松编辑数据并将其显示在我的前端。我正在考虑将注释以 JSON 形式存储在注释表中,但认为稍后编辑注释标题可能会更困难。

CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE)
CREATE TABLE notes(id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT UNIQUE, user_id FOREIGN KEY(user_id) REFERENCES users(id))

INSERT INTO users(name) VALUES('John')
INSERT INTO users(name) VALUES('Jane')

INSERT INTO notes(user_id, content) VALUES(1, "John's 1st Note")
INSERT INTO notes(user_id, content) VALUES(1, "John's 2nd Note")
INSERT INTO notes(user_id, content) VALUES(2, "Jane's 1st Note")

我正在尝试编写一个 select 语句,该语句将返回我的所有用户并将他们的笔记以 JSON 形式分组在一起。像这样返回的东西会很棒:

[name:John,notes:[{id:1, content:"John's 1st Note"},{id:2, content:"John's 2nd Note"}],
name: Jane,notes: [{id:3, content:"Jane's 1st Note"}]]

我尝试查看 group_concat() 和 json_group_array() 但我真的很难尝试将这些数据放在一起。

sql sqlite
1个回答
0
投票
SELECT 
    users.name,
    json_group_array(json_object('id', notes.id, 'content', notes.content)) AS notes
FROM 
    users 
LEFT JOIN 
    notes ON users.id = notes.user_id
GROUP BY 
    users.id;
© www.soinside.com 2019 - 2024. All rights reserved.