Postgresql

不同別名下的組合表

  • July 30, 2020

我有兩張桌子旅行和使用者。每當使用者發布旅行時,它將使用者的 id 儲存為外鍵。在獲取時,我將通過以下方式加入這兩個表。

詢問:

SELECT title, starting_point, ending_point, distance, trips.created_on 
FROM trips 
 JOIN users ON (users.id=trips.created_by);

結果:

{
           "title": "lorem ipsum",
           "starting_point": "Location A",
           "ending_point": "Location B",
           "distance": 20,
           "created_on": "2020-07-27T18:15:00.000Z",
           "author": "Test user"
       },

結果需要。

{
           "title": "lorem ipsum",
           "starting_point": "Location A",
           "ending_point": "Location B",
           "distance": 20,
           "created_on": "2020-07-27T18:15:00.000Z",
           "author": {
                      "id":1
                      "name": "Test user",
                      "role": "admin"
                     }
       },

簡而言之,我想將使用者表與trips表連接起來,但我想將使用者表的內容在trip中以不同的別名分開。

整排

您沒有提到 JSON,但您似乎在追求to_json(b)()或類似。例子:

SELECT t.*, to_json(u) AS author
FROM   trips t
JOIN   users u ON u.id = t.created_by;

或者,不涉及 JSON:

SELECT t.*, u AS author
FROM   trips t
JOIN   users u ON u.id = t.created_by;

然後author是一個 ROW 值,但沒有列名 - 該資訊僅在行類型的定義中。

選定的列

你後來評論說:

…如果我想idemail而且name只能users從桌子上?

JSON:

SELECT t.*
    , json_build_object('id', u.id, 'email', u.email, 'name', u.name)) AS author
FROM   trips t
JOIN   users u ON u.id = t.created_by;

或 ROW 值:

SELECT t.*
   , (SELECT x FROM (SELECT u.id, u.email, u.name) AS x)) AS author
FROM   trips t
JOIN   users u ON u.id = t.created_by;

看:

引用自:https://dba.stackexchange.com/questions/271967