Postgresql

解釋 OR 運算符在以下程式碼中的作用

  • February 23, 2021

我遇到了以下 SQL 程式碼,它(成功)輸出了父母列表和他們最小孩子的年齡:

SELECT parents.name AS name, MIN(children.age) AS age FROM people children
INNER JOIN people parents ON (parents.id = children.fatherId OR parents.id = children.motherId)
GROUP BY parents.id

程式碼 self 在其自身上加入了一個名為“people”的表。我只是想問 OR 運算符如何在這里工作?我知道 OR 是一個邏輯運算符,但在這裡它似乎做了別的事情。它需要兩個參數,並且只加入它們。它與邏輯或有什麼關係?

您可以查看它的另一種方式,這可能有助於您概念化,子句的ORofON就像使用 aUNION ALL並重複查詢並且僅利用每個OR案例的一個謂詞,如下所示:

-- Gets the fathers
SELECT parents.name AS name, MIN(children.age) AS age FROM people children
INNER JOIN people parents ON parents.id = children.fatherId
GROUP BY parents.id

UNION ALL

-- Gets the mothers
SELECT parents.name AS name, MIN(children.age) AS age FROM people children
INNER JOIN people parents ON parents.id = children.motherId
GROUP BY parents.id

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