【发布时间】:2014-03-05 16:55:35
【问题描述】:
我以 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 结果为真,最终将出现在我的结果中。
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
我认为必须有更好的过滤方式。非常感谢任何帮助。
【问题讨论】:
标签: sql foreign-keys foreign-key-relationship ms-access-2013