我們希望從DISTINCT
行c.ClassId
和c.ClassName
值其中:
class c.Id is named c.ClassName and costs c.Cost and is taught by c.InstructorId
AND customer c1.ID is named c1.FirstName c1.LastName and was born on c1.DateOfBirth
AND customer c2.ID is named c2.FirstName c2.LastName and was born on c2.DateOfBirth
AND c1.ID <> c2.ID
AND customer s1.CustomerId subscribed to s1.ClassId starting on s1.StartDate
AND customer s2.CustomerId subscribed to s2.ClassId starting on s2.StartDate
AND c1.ID = s1.CustomerId AND c2.ID = s2.CustomerId
AND c1.FirstName = 'Joe' AND c1.LastName = 'Bloggs'
AND c2.FirstName = 'John' AND c2.LastName = 'Snow'
AND s1.ClassId = c.ClassId AND s2.ClassId = c.ClassId
觀察到沒有重複的別名表保持S(一組)行,使一個真正的語句從報表模板(謂語)由數據庫設計與它的基表相關:
-- class c.Id is named c.ClassName and costs c.Cost and is taught by c.instructorId
FitnessClass c
-- cx.ID is named cx.FirstName cx.LastName and was born on cx.DateOfBirth
Customer cx
-- customer sx.CustomerId subscribed to class sx.ClassId starting on sx.StartDate
Subscription sx
觀察還,如果表達L
持有行滿足templateL
和表達R
保持行滿足templateR
然後
L JOIN R
保持滿足templateL AND templateR
- 行
R WHERE condition
擁有滿足templateR AND condition
templateR ON condition
行持有滿足templateR AND condition
行因此,我們要從中選擇行是:
FROM Class c
JOIN Customer c1 JOIN Customer c2
ON c1.ID <> c2.ID
JOIN Subscription s1 JOIN Subscription s2
WHERE
AND c1.ID = s1.CustomerId AND c2.ID = s2.CustomerId
AND c1.FirstName = 'Joe' AND c1.LastName = 'Bloggs'
AND c2.FirstName = 'John' AND c2.LastName = 'Snow'
AND s1.ClassId = c.ClassId AND s2.ClassId = c.ClassId
條件可以在相與任何順序只要每個只使用前面的JOIN或JOIN ON中的列。所以如果你認爲它更好,你可以按照其他順序重新排列這些。 (例如,本地化某些列名稱的使用。)(但您通過ON(或「,」不合適)必須組織的參數是specious。)
DISTINCT從FROM等生成的表中刪除非SELECTED列後刪除重複行。這樣做的結果是保留了滿足其模板的行的集合。 DISTINCT並不總是必要的。但你仍然需要不同的行。一般來說,你必須認爲關於你是否可以避免DISTINCT。有時你不能。有時候,你可以推斷你下一步做什麼與重複表格給出相同的答案,不管是否有重複。很少,要求的結果被允許有或應該有重複。但是,當通過簡單的關係模板表達式對應推理時,您無法進一步使用該結果。 (練習:查看是否有選擇的FROM等表返回正確的classid &的className值而不DISTINCT。)
(爲什麼你認爲LEFT JOIN爲宜目前還不清楚它返回什麼JOIN做,但。與無匹配的左錶行擴展NULL)。
請閱讀[問]和[mcve] s。 – philipxy
你究竟在哪裏試過?因爲'Bloggs'不是第一個名字。 – philipxy
最初是'John'而不是'Bloggs',只是一個抄錄錯誤 – alancussen