我叫兩個表user和post他們有這樣的資料:
用戶表
id | first_name | second_name
1 John Doe
2 Ellis Mount
帖子表
id | topic | body | author_id
1 Internet ...some text 1
2 Web 3.0 ...some text 2
所以我的問題是如何查詢posts其中的author用戶作為參考創建帖子的用戶的物件。
[
{
id:1,
topic: Internet,
body: ...some text,
author_id: 1
author: {
first_name: John,
last_name: Doe
}
},
{
id: 2,
topic: Web 3.0,
body: ...some text,
author_id: 2
author: {
first_name: Ellis,
last_name: Mount
}
}
]
所以,為了達到這個目的,我嘗試了類似這樣的`inner join:
SELECT *
FROM post
INNER JOIN user
ON post.author_id = user.id;
不幸的是,這沒有獲取我想要的資料......所以如果有人知道如何查詢請幫忙!
uj5u.com熱心網友回復:
您可以使用 JSON 格式并創建 JSON 檔案。
演示
SELECT
post.*,
json_build_object(
'first_name',
first_name,
'last_name',
second_name
) as author
FROM post
INNER JOIN "user"
ON post.author_id = "user".id;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391481.html
標籤:数据库 PostgreSQL的
下一篇:用一些限制替換字符
