![](/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.