【问题标题】:What is the equivalent for a Group By and Having clause query in Relational Algebra?关系代数中 Group By 和 Have 子句查询的等价物是什么?
【发布时间】:2012-05-05 16:33:43
【问题描述】:

示例:

7.查找同一天拜访过同一专业的两位不同医生的患者。

   SELECT       p.pid , d.speciality, v.date
   FROM         Patient p
   JOIN         Visits v ON v.pid = p.pid
   JOIN         Doctors d ON d.did = v.did
   GROUP BY     p.pname, d.speciality, v.date
   HAVING   COUNT(DISTINCT d.did) = 2

您如何为此编写合法的 RA?

RA 中 GroupBy 和 Have 子句基本上是什么等价的?

同样被问到但没有得到回答here

【问题讨论】:

标签: sql relational-algebra


【解决方案1】:

您实际上不需要尝试转换 SQL,反映问题也提供了 RA 解决方案:

“查找同一天拜访过同一专业的两位不同医生的患者”

我们首先将患者、就诊和医生结合起来

Patients x Visits x Doctors

由于我们有两次就诊和两名医生,我们需要另一个表访问和医生的实例。我们不能照原样使用它们,否则我们将无法区分它们。因此,重命名\rho

Patients x \rho_V1(Visits) x \rho_D1(Doctors) x \rho_V2(Visits) x \rho_D2(Doctors)

接下来我们需要选择“匹配”的组合

\sigma_{Patients.pid = V1.pid /\ 
        Patients.pid = V2.pid /\ 
        V1.date = V2.date /\ 
        V1.did = D1.did /\ 
        V2.did = D2.did /\
        D1.did != D2.did /\
        D1.speciality = D2.speciality}
 (Patients x \rho_V1(Visits) x \rho_D1(Doctors)  x 
             \rho_V2(Visits) x \rho_D2(Doctors))

接下来我们需要找到患者,即pid上的项目

\pi_{Patients.pid} 
(\sigma_{Patients.pid = V1.pid /\ 
        Patients.pid = V2.pid /\ 
        V1.date = V2.date /\ 
        V1.did = D1.did /\ 
        V2.did = D2.did /\
        D1.did != D2.did /\
        D1.speciality = D2.speciality}
 (Patients x \rho_V1(Visits) x \rho_D1(Doctors)  x 
             \rho_V2(Visits) x \rho_D2(Doctors)))

通过这种方式,您找到了在同一天拜访了至少位同一专业的两位不同医生的患者。如果您需要找到那些恰好访问过两位医生的患者,您应该记住恰好 2 = 至少 2 - 至少 3,即,

\pi_{Patients.pid} 
(\sigma_{Patients.pid = V1.pid /\ 
        Patients.pid = V2.pid /\ 
        V1.date = V2.date /\ 
        V1.did = D1.did /\ 
        V2.did = D2.did /\
        D1.did != D2.did /\
        D1.speciality = D2.speciality}
 (Patients x \rho_V1(Visits) x \rho_D1(Doctors)  x 
             \rho_V2(Visits) x \rho_D2(Doctors)))
-
\pi_{Patients.pid} 
(\sigma_{Patients.pid = V1.pid /\ 
        Patients.pid = V2.pid /\ 
        Paitents.pid = V3.pid /\
        V1.date = V2.date /\ 
        V2.date = V3.date /\
        V1.did = D1.did /\ 
        V2.did = D2.did /\
        V3.did = D3.did /\
        D1.did != D2.did /\
        D1.did != D3.did /\
        D2.did != D3.did /\
        D1.speciality = D2.speciality /\
        D2.speciality = D3.speciality}
 (Patients x \rho_V1(Visits) x \rho_D1(Doctors)  x 
             \rho_V2(Visits) x \rho_D2(Doctors)  x
             \rho_V3(Visits) x \rho_D3(Doctors) ))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多