繁体   English   中英

SQL查询以基于其他列过滤列

[英]SQL query to filter column based on other columns

我有一个类似下面的关系表:

我想编写一个查询,如果我输入tag_id,我需要根据以下规则获取video_id。 如果标签属于同一类别,则标签之间的OR条件。 如果标签属于不同类别,则标签之间的AND条件

tag_id  pvid_id     cat_id  
1       1           1   
1       2           1   
2       2           2

在以上示例中,

如果我给tag_id 1作为输入,则pvid_id的预期输出为1,2

如果我给tag_id 1,2作为输入,则pvid_id的预期输出为2

我无法进行查询,有人可以帮我解决这个问题,或者为我提供解决方案的指导吗?

谢谢

一次输入

Select tag_id, 
group_concat(distinct pvid_id) 
from your_table where tag_id=1 
group by tag_id

对于多个输入

Select tag_id, 
group_concat(distinct pvid_id) 
from your_table where tag_id 
in('1','2')
group by tag_id

使用group_concat

select group_concat(pvid_id separator ', ') as result
  from tab
 where tag_id = 1 -- or tag_id = 2

result
 1, 2

SQL小提琴演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM