上面是我的架构的屏幕上限。
访问表有一个个人ID号列表,ICD是一个与某个人有关的代码列表。您可以从联结表中看到Visits和ICDTable之间存在多对多关系。我正在尝试进行一个查询,允许一个人在ICDTable中键入两个记录,如果一个人同时拥有这两个记录,则只返回访问ID#。我试图从我之前写的一个查询中修改它,但我无法弄清楚发生了什么。查询本身并没有“失败”,因为它允许我搜索某些东西,但这显然是错误的。我错过了什么?格拉西亚斯。
SELECT Visits.ID, Inf.desc, Sore.desc
FROM tblKentuckyCounties
INNER JOIN
(
ICDTable AS Inf
INNER JOIN
(
(
(
Visits
INNER JOIN ICDTable AS InfVisits
ON Visits.ID=InfVisits.VisitsID
)
INNER JOIN ICDTable AS SoreVisits
ON Visits.ID=SoreVisits.ID
)
INNER JOIN ICDTable AS Sore
ON SoreVisits.ICD_IDFK=Sore.ID
) ON Inf.ID=Visits.ICD_IDFK
)
ON tblKentuckyCounties.ID=Visits.County
WHERE Inf.desc=[enter first term]
AND Sore.desc=[enter second term]
感谢编辑。
好的,所以我发现了我需要做的事情。在本文下面是对任何对如何做这类事情感兴趣的人的工作查询
SELECT DISTINCT Visits.KHA_ID, Visits.totalCharges
FROM (Visits INNER JOIN (ICDTable INNER JOIN ICDVisitsJxn ON ICDTable.ICD9ID = ICDVisitsJxn.ICD_IDFK) ON Visits.ID = ICDVisitsJxn.VisitsIDFK) INNER JOIN (ICDTable AS ICDTable_1 INNER JOIN ICDVisitsJxn AS ICDVisitsJxn_1 ON ICDTable_1.ICD9ID = ICDVisitsJxn_1.ICD_IDFK) ON Visits.ID = ICDVisitsJxn_1.VisitsIDFK
WHERE (((ICDTable.Description) Like [enter term]) AND ((ICDTable_1.Description) Like [enter another term]));
答案 0 :(得分:2)
您可以将查询划分为仅包含ICDVisits和ICDtable(1)的子查询。在新查询中,您将使用此子查询加入Visits两次(2)。
(1)
SELECT ICDTable.Description, ICDVisits.VisitsIDFK
FROM ICDTable INNER JOIN ICDVisits ON ICDTable.ICD9ID = ICDVisits.ICD_IDFK;
(2)
SELECT Visits.ID
FROM query1 INNER JOIN (query2 INNER JOIN Visits ON query2.VisitsIDFK = Visits.ID) ON
query1.VisitsIDFK = Visits.ID
WHERE (((query1.Description) Like 'a') AND ((query2.Description) Like 'b'));
(查询1和2是ICDVisits和ICDTable的连接)。
忘记提及:您不必使用ICDVisitsJxn中的ID字段作为主键,您可以将VisitsIDFK和ICD_IDFK字段作为主键。这样可以避免重复输入。
查询1& 2(显然是相同的):
综合查询: