例如:
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和Having Clause的等价?
同样被问到并没有得到回答here
答案 0 :(得分:4)
你真的不需要尝试转换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) ))