具有冗余约束的多对多 SQL 查询
令人惊讶的是,我没有找到任何关于我的问题的信息。我希望我没有找得太糟糕。
因此,我得到了三个表,我们称它们为:文档、主题和多对多过渡表 DocumentsTopics
我需要能够查找一些文档仅“包含”主题 8 和 15。我该怎么办?因为在下面的例子中:
select Documents.title from Documents
inner join DocumentsTopics
on Documents.PK_DOC = DocumentsTopics.FK_DOC
inner join Topics
on DocumentsTopics.FK_TOPICS = Topics.PK_TOPICS
where Topics.PK_TOPICS=8 and Topics.PK_TOPICS=15;
“where”显然是不可能的。非常感谢那些可以提供帮助的人!
克里斯托夫
Surprisely, I didn't found anything about my question. I hope I didn't looked for it too bad.
So, I got three tables, let's call them : Documents, Topics, and the many-to-many transitionnal table DocumentsTopics
I need to able to look for some Documents that "contains" topic 8 and 15 only. How do I do ? Because in the following example :
select Documents.title from Documents
inner join DocumentsTopics
on Documents.PK_DOC = DocumentsTopics.FK_DOC
inner join Topics
on DocumentsTopics.FK_TOPICS = Topics.PK_TOPICS
where Topics.PK_TOPICS=8 and Topics.PK_TOPICS=15;
The "where" is obviously impossible. Thanks a lot to those who can help !
Christophe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果仅应显示主题 8 和 15 都存在的文档,则以下任一方法(以及其他几种方法)都有效 - 检查查询计划等的性能。第二个对我来说表现更好。
If only documents where both topics 8 and 15 exist should be shown, then either of the below approaches (plus several more) work - check the query plan etc for performance. The second performs better for me.
嗯,我想我的描述不是很清楚。但我找到的解决方案是分步进行,不只使用 SQL,而是使用 PHP。
我用第一个标准进行了第一次研究:
我在 PHP 数组中得到了结果。然后,第二个,具有第二个标准:
我在另一个临时 PHP 数组中得到结果。
然后我使用 PHP array_intersect():
只查找与两个条件匹配的结果。显然,我可以重复使用 $results 来进行多次交叉。因此,搜索标准没有限制。
希望这有帮助……
Well I think I wasn't very clear in my description. But the solution I found out is to proceed by steps, without using only SQL, but with PHP.
I do a first reasearch with the first criterium :
I get the result in a PHP array. Then, a second one, with the second criterium :
I get the results in another, temporary PHP array.
And then I use PHP array_intersect() :
to find only the results that are matching both criteriums. Obviously, I can reuse $results to intersect as many time as I want. So, no limits to search criteriums.
Hope this help…