多对多关系,使查询不那么复杂
这只是我的标签系统中使用的表格设计的一个示例。
ARTICLES
id
content
TAGS
id
tag
TAGSTOARTICLES
articleid
tagid
@edit 最后,经过一些rubberducking之后,我成功编写了以下查询:
仅选择文章:
SELECT a.id, a.content, GROUP_CONCAT(t.tag) AS tags
FROM articles a
LEFT JOIN tagstoarticles tta ON tta.articleid = a.id
LEFT JOIN tags t ON t.id = tta.tagid
GROUP BY a.id
结果:
id content GROUP_CONCAT(t.tag)
1 Lorem ipsum 1 tag1,tag2
2 Lorem ipsum 2 tag1
3 Lorem ipsum 3 tag2
搜索标签:
SELECT a.id, a.content, GROUP_CONCAT(t.tag) AS tags
FROM articles a
LEFT JOIN tagstoarticles tta ON tta.articleid = a.id
LEFT JOIN tags t ON t.id = tta.tagid
WHERE a.id IN (SELECT A.id FROM tagstoarticles M, articles A, tags T
WHERE M.tagid = T.id
AND (T.tag IN ('tag1'))
AND A.id = M.articleid
GROUP BY A.id
HAVING COUNT( A.id )=1
)
GROUP BY a.id
结果:
id content GROUP_CONCAT(t.tag)
1 Lorem ipsum 1 tag1,tag2
2 Lorem ipsum 2 tag1
但是用于搜索标签的查询很混乱,有什么办法可以更轻松地解决这个问题吗?
This is just an example of the tables design used in my tags system.
ARTICLES
id
content
TAGS
id
tag
TAGSTOARTICLES
articleid
tagid
@edit Finally after some rubberducking I managed to write following queries:
Just selecting articles:
SELECT a.id, a.content, GROUP_CONCAT(t.tag) AS tags
FROM articles a
LEFT JOIN tagstoarticles tta ON tta.articleid = a.id
LEFT JOIN tags t ON t.id = tta.tagid
GROUP BY a.id
Result:
id content GROUP_CONCAT(t.tag)
1 Lorem ipsum 1 tag1,tag2
2 Lorem ipsum 2 tag1
3 Lorem ipsum 3 tag2
Searching for tags:
SELECT a.id, a.content, GROUP_CONCAT(t.tag) AS tags
FROM articles a
LEFT JOIN tagstoarticles tta ON tta.articleid = a.id
LEFT JOIN tags t ON t.id = tta.tagid
WHERE a.id IN (SELECT A.id FROM tagstoarticles M, articles A, tags T
WHERE M.tagid = T.id
AND (T.tag IN ('tag1'))
AND A.id = M.articleid
GROUP BY A.id
HAVING COUNT( A.id )=1
)
GROUP BY a.id
Result:
id content GROUP_CONCAT(t.tag)
1 Lorem ipsum 1 tag1,tag2
2 Lorem ipsum 2 tag1
But the query used for searching for tags is a mess, any idea to solve this easier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“但是如何修改这个查询以同时选择分配给这篇文章的所有标签呢?”
“当我只想获得结果而不通过标签搜索时,该怎么做?”
这为每个标签提供了一个不同的结果行,因此您必须应用一些后处理才能将其转换为带有标签的文章列表。但是,通过按文章 ID 排序,您可以确保一篇文章的所有标签都一起返回。
"But how to modify this query to select all tags assigned to this article at the same time?"
"And how to do this when I just want to get the results without searching by tags?"
This gives you a distinct result row for each tag, so you'll have to apply a bit of postprocessing to convert this into a list of articles with tags. However by sorting by article id, you can be sure that all the tags for one article are returned together.