【问题标题】:SQL query to filter column based on other columns基于其他列过滤列的 SQL 查询
【发布时间】:2018-07-07 19:48:23
【问题描述】:

我有一个如下所示的关系表:

我想编写一个查询,如果我输入 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

我无法提出查询,有人可以帮我解决这个问题或给我一个解决方案的方向吗?

谢谢

【问题讨论】:

    标签: mysql sql relational-database relationship


    【解决方案1】:

    一次输入

    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
    

    【讨论】:

      【解决方案2】:

      使用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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-03
        • 2022-01-20
        • 2010-10-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2013-06-08
        • 1970-01-01
        相关资源
        最近更新 更多