我是SQL新手。我有一个包含两个表的数据库:用户和集合。表“用户”存储应用程序的用户,而“集合”存储项目的集合。每个集合均由一个用户拥有。
我需要获取带有集合及其所有者的JSON对象。
例如:
[
{
"collection_id": 23,
"collection_name": "The Beatles Albums"
"owner": {
"user_id": 5,
"first_name": "John",
"last_name": "Doe"
}
}
]
这是我尝试过的:
router.get('/collections/', (req, res) => {
mysqlconnection.query('SELECT * FROM collections INNER JOIN users ON collections.OwnerID = users.id WHERE collections.OwnerID = users.id ', (err, rows, fields) => {
if(!err) {
res.json(rows);
} else {
console.log(err);
}
})
})
这就是我得到的:
[
{
"collection_id": 23,
"collection_name": "The Beatles Albums",
"owner": 5,
"user_id": 5,
"first_name": "John",
"last_name": "Doe"
}
]
我是SQL新手。非常感谢您的帮助。
我相信MYSQL JSON_OBJECT可以解决您的问题。尝试为此更改查询:
SELECT
JSON_ARRAYAGG(
JSON_OBJECT(
'collection_id', collections.collection_id,
'collection_name', collections.collection_name,
'owner', JSON_OBJECT(
'user_id', users.user_id,
'first_name', users.first_name,
'last_name', users.last_name
)
)
)
FROM
collections
INNER JOIN
users
ON collections.OwnerID = users.id
WHERE collections.OwnerID = users.id '