查询以根据标记查找主题

Sal*_*lil 8 mysql sql ruby-on-rails

我想在我的应用程序中搜索以下数据的搜索功能

topic_id   tag
1          cricket
1          football
2          football
2          basketball
3          cricket
3          basketball
4          chess
4          basketball
Run Code Online (Sandbox Code Playgroud)

现在当我搜索术语cricket AND footballo/p应该是

 topic_id
    1
Run Code Online (Sandbox Code Playgroud)

当我搜索术语cricket OR footballo/p应该是

 topic_id
    1
    2
    3
Run Code Online (Sandbox Code Playgroud)

我尝试下面的事情

为了和

  select topic_id from table_name where tag like "%cricket%" and topic_id in (select topic_id from table_name where tag like "%football%")
Run Code Online (Sandbox Code Playgroud)

为或

 select topic_id from table_name where tag like "%cricket%" OR tag like "%football%"
Run Code Online (Sandbox Code Playgroud)

我的问题是当用户搜索cricket AND football AND basketball AND chess我的查询变得非常可悲时

对此有任何简单的解决方案.我也试过GROUP_CONCAT但是徒劳无功

bra*_*ing 1

您需要进行自加入

select distinct topic_id from 
table_name as t1
join
table_name as t2 
on 
t1.topic_id = t2.topic_id
and
t1.tag = "cricket"
and
t2.tag = "football"
Run Code Online (Sandbox Code Playgroud)