![](/img/trans.png)
[英]Joining tables and selecting foreign key where all rows meet condition in first table
[英]Selecting records from Foreign Key table where multiple items match the condition
我從第三方以MS Access 2000文件格式的下表形式獲取數據
以下是這些表中的示例數據。
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 |
+----+----------+----------------------------------------+
現在,我的最終用戶將傳遞一個或多個TagID,例如15和18,我的目標是找到具有所有這些TagID的所有 PaperID。 在這些示例中,我需要返回663和659
我在下面的查詢中嘗試過,但是如果數據中有任何故障,那么它將無法正常工作。 例如,PaperID 662在表中以相同的TagID出現兩次,因此count(PaperID)= 2變為true,它將最終出現在我的結果中。
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 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.