Alias

SQL中同一張表的兩個連接

  • March 3, 2020

我有 2 個 SQL 表:NAMES並且RELATIONSHIPS目前NAMES只有 2 列:namename_id. 另一個是表中人員之間的關係NAMES列表。它有 3 列:primaryperson_idrelatedperson_idrelationship_idprimaryperson_idrelated_person_id是表中的name_ids NAMES。每個人都NAMES可以在的主要列或相關列中有多個條目RELATIONSHIPS(這是多對多關係嗎?)。

此查詢有效:

SELECT  people.name AS 'primary', relationships.related_person_id AS relatedto
FROM relationships
JOIN people
ON people.name_id=relationships.primary_person_id 
ORDER BY people.name_id;

但我想在relatedto列中顯示一個名稱(即文本)而不是 ID 號。我怎樣才能做到這一點?

您可以在連接表時分配表別名,就像您對列名所做的那樣。它不僅為您節省了大量的打字,而且使程式碼更具可讀性,並且解決了兩次加入同一張表的問題。

SELECT p1.name AS "primary",
      relationships.related_person_id AS relatedto,
      p2.name AS related_name
FROM people AS p1
INNER JOIN relationships AS r
   ON p1.name_id=r.primary_person_id 
INNER JOIN people AS p2
   ON p2.name_id=r.related_person_id 
ORDER BY p1.name_id;

在上面的範例中,我已將p1and分配p2people表和rrelationships

注意:一些數據庫平台不喜歡“AS”關鍵字。如果需要,您可以一起跳過“AS”,如下所示:

...
FROM people p1
INNER JOIN relationships r
...

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