复杂的子查询 - 这可能吗?
我有两张表:一张存储标签,另一张存储文章。有一种模式“按标签获取文章”,它基本上获取所有标记为“x”的文章。在我的文章表中,我使用一个名为 Tags
的字段,它以“tag1、tag2、tag3...”这样的模式存储数据。
所以我想通过像这样的单个查询来完成所有工作:
SELECT *,
(SELECT tagname
FROM `tags_table`
WHERE tagurn LIKE 'x') as TAGNAME
FROM `articles_table`
WHERE (Tags LIKE 'TAGNAME,%' OR Tags LIKE '%, TAGNAME' ... and so on)
我不知道它是否可能,但我真的很想使用单个查询(带有子查询)而不是两个不同的查询。
I've got 2 tables: one stores tags, the other stores articles. There's a mode "Get articles by tag", which basically takes all articles, tagged "x". In my articles table I use a filed, called Tags
, that stores data in such pattern 'tag1, tag2, tag3, ...'.
So I want to get everything work by just a single query like that:
SELECT *,
(SELECT tagname
FROM `tags_table`
WHERE tagurn LIKE 'x') as TAGNAME
FROM `articles_table`
WHERE (Tags LIKE 'TAGNAME,%' OR Tags LIKE '%, TAGNAME' ... and so on)
I don't know if it's even possible, but I'd really like to use a single query (with a sub-query) instead of two different.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是在数据库中存储多对多关系的错误方法。
您应该有这样的架构:
[PK]
= 主键,[FK]
= 外键其中
articles_tags
是一个连接表。现在,您可以使用给定标签获取所有文章(如果您知道tag_id
,您甚至不需要JOIN
):This is the wrong way to store a many-to-many relationship in a database.
You should have a schema like:
[PK]
= primary key,[FK]
= foreign keyWhere
articles_tags
is a junction table. Now, you can get all articles with a given tag with (if you know thetag_id
you won't even need theJOIN
):