[英]Select data from the ends of a many-to-many relationship
I have a database of posts, each of which have tags. 我有一个帖子数据库,每个帖子都有标签。 These tables are named Posts
and Tags
respectively. 这些表分别命名为Posts
和Tags
。 I also have a third table, called Posts_Tags
which maintains a many-to-many relationship between these two tables. 我还有一个名为Posts_Tags
的第三个表,它维护这两个表之间的多对多关系。
In order to do this, both my posts and my tags tables have an id
column. 为此,我的帖子和我的标签表都有一个id
列。 My Posts_Tags
table, therefore, has both a postid
and tagid
column to store the mappings. 因此,My Posts_Tags
表具有postid
和tagid
列来存储映射。
I am querying, for example, all posts with the word "class" in the title. 例如,我在标题中查询所有带有“class”字样的帖子。 I can do this easily with this query: 我可以使用此查询轻松完成此操作:
SELECT * FROM Posts WHERE title LIKE '%{class}%'
However, now I want to query all posts which not only have "class" in the title, but are also tagged with the "Java" tag. 但是,现在我想查询所有帖子,这些帖子不仅在标题中有“class”,而且还标有“Java”标签。 I could do this in two separate queries, where I first get the id of the Java tag: 我可以在两个单独的查询中执行此操作,其中我首先获取Java标记的id:
SELECT id FROM Tags WHERE name='Java'
Then I could plug that into my first query, like this: 然后我可以将其插入到我的第一个查询中,如下所示:
SELECT Posts.*
FROM Posts
INNER JOIN Posts_Tags
ON Posts.id=Posts_Tags.postid
WHERE Posts_Tags.tagid='$java_tag_id'
AND title LIKE '%{class}%'
However, I know I can do this in a single query, I just don't know how. 但是,我知道我可以在一个查询中执行此操作,我只是不知道如何。 I still have to think a lot about joins when doing just one, and doing multiple joins in the same query makes my head spin. 在做一个连接时我仍然需要考虑很多关于连接的事情,并且在同一个查询中进行多个连接会让我头晕目眩。 How should I structure my query to perform this operation? 我应该如何构造我的查询来执行此操作?
SELECT p.*
FROM Posts p
JOIN Posts_Tags pt
ON pt.postid = p.id
JOIN tags t
ON t.id = pt.tagid
WHERE t.tag='java'
AND p.title LIKE '%{class}%';
SELECT
p.*
FROM posts as p
INNER JOIN Posts_Tags pt ON pt.post_id = p.id
INNER JOIN Tags as t ON pt.tags_id = t.id
WHERE t.tag='java'
AND p.title LIKE '%keyword%';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.