0

我從第三方MS Access 2000文件格式獲取數據在下面表格形式選擇記錄,其中多個項目匹配

  • 論文和
  • PaperTags
  • 條件

下面是來自這些表格的示例數據。

Papers表和樣本數據

+----+----------+ 
| ID | PaperID | 
+----+----------+ 
| 1 | 658  | 
| 2 | 659  | 
| 3 | 660  | 
| 4 | 661  | 
| 5 | 662  | 
| 6 | 663  | 
| 7 | 664  | 
+----+----------+ 

PaperTags表和樣本數據

+----+----------+----------------------------------------+ 
| ID | PaperID |     TagID    | 
+----+----------+----------------------------------------+ 
| 1 | 663  | 3         | 
| 2 | 663  | 15 --Y        | 
| 3 | 663  | 17         | 
| 4 | 663  | 18 --Y        | 
| 5 | 664  | 14         | 
| 62 | 658  | 9         | 
| 63 | 658  | 14         | 
| 64 | 658  | 17         | 
| 65 | 659  | 15 --Y        | 
| 66 | 659  | 17         | 
| 67 | 659  | 18 --Y        | 
| 68 | 660  | 17         | 
| 69 | 660  | 18 --N as it has only 18 and not 15 | 
| 70 | 661  | 10         | 
| 71 | 661  | 17         | 
| 72 | 661  | 18 --N as it has only 18 and not 15 | 
| 73 | 662  | 18 --N as it has only 18 and not 15 | 
| 74 | 662  | 14         | 
| 75 | 662  | 17         | 
| 76 | 662  | 18 --N as it has only 18 and not 15 | 
+----+----------+----------------------------------------+ 

現在我的最終用戶將通過例如15和18我的目標的一個或多個TagIDs是找到所有的這些TagID具有全部的PaperID。在這些例子中,我需要返回663和659

我試過下面的查詢,但如果數據有任何故障,那麼它不起作用。例如,PaperID 662在表格中出現兩次,具有相同的TagID,因此計數(PaperID)= 2的結果是正確的,並且最終會顯示在我的結果中。

select Count(PaperID), PaperID from PaperTags 
group by TagID, PaperID 
having TagID = 15 or TagID = 18 
and count(PaperID) = 2 

,我試過其他查詢是

select * from Papers 
where Papers.PaperID 
in 
(
select PaperTags.PaperID from PaperTags 
where (PaperTags.Tagid = 15 or PaperTags.Tagid = 18) 
and PaperTags.PaperID = Papers.PaperID 
) 

我已經直通下面的文章,但因爲我使用MSACCESS我不能使用這種方法。

Select records from a table where all other records with same foreign key have a certain value

我認爲必須有更好的方式來進行篩選。任何幫助深表感謝。

回答

0

事情是這樣的:

SELECT G.ContentID 
FROM (
SELECT PT.ContentID, PT.TagID 
FROM PaperTags AS PT 
WHERE PT.TagID IN (15, 18) 
GROUP BY PT.ContentID, PT.TagID 
) AS G 
GROUP BY G.ContentId 
HAVING Count(*) = 2 
+0

@T基翁 - 在訪問我收到錯誤「語法錯誤(缺少操作員)在查詢表達式‘計數(DISTINCT內容識別)’」我測試了一個簡單的查詢與伯爵( DISTINCT ContentID),仍然得到了同樣的錯誤,我認爲MS Access不支持Count(DISTINCT ColumnName) – ndd

+0

呃..嗯...我想... –

+0

我已經更新了我的答案。 –