简体   繁体   English

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

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

I have a relational table that looks something like below: 我有一个类似下面的关系表:

I want to write a query to which if i give a input of tag_id i need to get the video_id based on the following rule. 我想编写一个查询,如果我输入tag_id,我需要根据以下规则获取video_id。 If the tags belong to the same category then OR condition between tags. 如果标签属于同一类别,则标签之间的OR条件。 If tags belong to different category then AND condition between the tags 如果标签属于不同类别,则标签之间的AND条件

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

In the above example, 在以上示例中,

If i give tag_id 1 as the input, the expected output of pvid_id as 1,2 如果我给tag_id 1作为输入,则pvid_id的预期输出为1,2

If i give tag_id 1,2 as the input, the expected output of pvid_id is 2 如果我给tag_id 1,2作为输入,则pvid_id的预期输出为2

I am unable to fromulate the query, can someone please help me with it or give me a direction towards getting the solution? 我无法进行查询,有人可以帮我解决这个问题,或者为我提供解决方案的指导吗?

Thanks 谢谢

For one input 一次输入

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

For multiple inputs 对于多个输入

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

Use group_concat : 使用group_concat

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

result
 1, 2

SQL Fiddle Demo SQL小提琴演示

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

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