从外键表中选择多个项匹配条件的记录

时间:2014-03-05 16:55:36

标签: sql foreign-keys foreign-key-relationship ms-access-2013

我以 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  |
+----+----------+----------------------------------------+

现在,我的最终用户将传递一个或多个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

我认为必须有更好的过滤方法。非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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