【发布时间】:2021-07-31 13:03:46
【问题描述】:
我有一个posts表,每个post都有标签,每个标签都有一个topic,例如:
Post name: Anything
Post tag: 1, 2, 3
1: is the id of Male
2: is the id of United States
3: is the id of India
1标签属于性别话题,2和3标签属于国家话题。
这里的表格是这样的:
posts:
- id
- name
tags:
- id
- name
- topic_id
topics:
- id
- name
tags_posts:
- tag_id
- post_id
如果用户在 UI 上选择了 Male 和 United States,现在我想做一个这样的过滤器,所以我应该选择所有带有 Male 和 United States 标签的帖子。
SELECT * FROM posts where tag_relation = Male and tag_relation = United States
tag_relation here means JOIN to tags_posts table
但如果用户在 UI 上选择了男性、美国和印度,那么我应该选择所有具有男性和(美国或印度)标签的帖子。
SELECT * FROM posts where tag_relation = Male and (tag_relation = United States or tag_relation = India)
tag_relation here means JOIN to tags_posts table
你可以看到标签是否属于同一个主题,哪里应该是OR,但如果它们属于不同的主题,那么哪里应该是AND。
所以这里的问题是我如何加入主题表并检查所选标签是否是同一主题并根据主题对所选标签进行分组,然后根据该主题执行位置。
【问题讨论】: