我有以下架构,其中有person, phone and address
表。 Person
表与phone and address
表之间的关系为1到0到多个。
我正在尝试输出以下结果,但由于我正在学习并且正在做这些,因此我没有想法。如何通过我写的这个查询得到以下结果,我得到相同的结果,但是在2行?
+------+--------+----------------+----------------+
| NAME | MRN_NB | HOME_PHONE_NBR | WORK_PHONE_NBR |
+------+--------+----------------+----------------+
| John | 222 | 415-222-3333 | 510-333-4444 |
+------+--------+----------------+----------------+
QUERY -
SELECT P.NAME, P.MRN_NB, PN.PHONE_NBR
FROM PERSON P
INNER JOIN PHONE PN ON P.ID = PN.ID
Where P.MRN_NB = (Select
T.MRN_NB from PERSON T inner join PHONE U on T.ID=U.ID where
U.USG_TYP='HOME' or U.USG_TYP='WORK' group by T.MRN_NB having
COUNT(T.MRN_NB)>1)
对我的查询进行哪些修改以返回所有具有工作号但没有home
数字且输出类似的行?
+------+--------+--------------+
| NAME | MRN_NB | PHONE_NBR |
+------+--------+--------------+
| Bill | 444 | 650-444-5555 |
+------+--------+--------------+
答案 0 :(得分:0)
对于您的第一个要求,即在一行中显示两行数据,我们可以使用left join
两次使用相同的表 -
select p.NAME, p.MRN_NB, ph.PHONE_NBR as HOME_PHONE_NBR, pw.PHONE_NBR as WORK_PHONE_NBR
from Person as p
left join Phone as ph on ph.ID = p.ID and ph.USG_TYPE = 'HOME'
left join Phone as pw on pw.ID = p.ID and pw.USG_TYPE = 'WORK'
输出 -
NAME MRN_NB HOME_PHONE_NBR WORK_PHONE_NBR
JOHN 111 2424234 6464
对于您的第二个要求,即仅显示没有HOME
个号码的人 -
select p.NAME, p.MRN_NB, max(pn.PHONE_NBR)
from Person as p
inner join phone as pn on pn.ID = p.ID and pn.USG_TYPE is not null
group by p.ID, p.NAME, p.MRN_NB
having sum(case pn.USG_TYPE when 'home' then 1 else 0 end) = 0
输出 -
NAME MRN_NB PHONE_NBR
ROHTI 222 78686
答案 1 :(得分:0)
我会使用JOIN
和NOT EXISTS
:
SELECT P.NAME, P.MRN_NB, PN.PHONE_NBR
FROM PERSON P INNER JOIN
PHONE PN
ON P.ID = PN.ID
WHERE PN.USG_TYP = 'WORK' AND
NOT EXISTS (SELECT 1
FROM PHONE PN2
WHERE PN2.ID = PN.ID AND PN2.USG_TYP = 'HOME'
);