我无法解决以下问题。前几天我学习了如何使用 JSON1 系列函数,但这一次似乎更像是一个 SQL 问题。
这是我的数据库设置:
CREATE TABLE persons(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE)
CREATE TABLE interests(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE)
CREATE TABLE persons_interests(person INTEGER, interest INTEGER, FOREIGN KEY(person) REFERENCES persons(id), FOREIGN KEY(interest) REFERENCES interests(id))
INSERT INTO persons(name) VALUES('John')
INSERT INTO persons(name) VALUES('Jane')
INSERT INTO interests(name) VALUES('Cooking')
INSERT INTO interests(name) VALUES('Gardening')
INSERT INTO interests(name) VALUES('Relaxing')
INSERT INTO persons_interests VALUES(1, 1)
INSERT INTO persons_interests VALUES(1, 2)
INSERT INTO persons_interests VALUES(2, 3)
基于这些数据,我想得到以下输出,这是聚合到单个 JSON 数组中的所有人的所有兴趣:
[{name: John, interests:[{name: Cooking},{name: Gardening}]}, {name: Jane, interests:[{name: Relaxing}]}]
现在以下是我尝试做的。不用说,这并没有给我想要的东西:
SELECT p.name, json_object('interests', json_group_array(json_object('name', i.name))) interests
FROM persons p, interests i
JOIN persons_interests pi ON pi.person = p.id AND pi.interest = i.id
不想要的输出是:
John|{"interests":[{"name":"Cooking"},{"name":"Gardening"},{"name":"Relaxing"}]}
非常感谢任何帮助!