【问题标题】:SQL: Select only rows fullfilling conditions via relation tableSQL:仅选择满足关系表条件的行
【发布时间】:2019-05-16 09:56:08
【问题描述】:

我有两个表,只有当第二个表中的所有特定条件都满足时,我才需要从第一个表中选择值。让我们通过一个例子来解释一下。

第一张桌子

id       movie    
---|--------------
1  | Matrix       
2  | Pulp Fiction 
3  | Avengers     
4  | Commando     

第二张表

id    movie_id    user_id
---|-----------|---
1  | 1         |  1
2  | 1         |  2
3  | 1         |  3
4  | 2         |  1
5  | 2         |  4
6  | 3         |  2
7  | 4         |  1
8  | 4         |  3

从这些表格中,我只需要找出用户 1 和 3 看过的电影。所以结果我需要看看

想要的结果

id    movie   
---|--------
1  | Matrix      
4  | Commando

我尝试了一些查询,但无法掌握最终结果。 最后,我将“构造”这个查询基于选择作为输入的用户。所以最后,可能还有 5 个用户,我只需要找到他们都看过的电影。所以请记住这一点。

感谢所有帮助和想法,谢谢。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    你可以试试下面-

    select b.id, b.movie from 
    Secondtable a inner join Firsttable b 
    on a.movie_id=b.id 
    where user_id in (1,3)
    group by b.id, b.movie
    having count(distinct user_id)=2
    

    【讨论】:

    • ...谢谢,完全按照我的需要工作 :) (+ 你在预期结果中修复了错误的 ID :D)
    【解决方案2】:

    一种方法使用group byhaving

    select t1.id, t1.name
    from t1 join
         t2
         on t1.id = t2.movie_id
    where t2.user_id in (1, 3)
    group by t1.id, t1.name
    having count(*) = 2;
    

    这种方法在它可以实现的逻辑上非常灵活——基本上是通过更改having 子句。

    我建议不使用聚合的替代方案使用exists

    select t1.*
    from t1
    where exists (select 1
                  from t2
                  where t2.movie_id = t1.id and t2.user_id = 1
                 ) and
          exists (select 1
                  from t2
                  where t2.movie_id = t1.id and t2.user_id = 3
                 );
    

    t2(movie_id, user_id) 上有一个索引,这可能是所有替代品中性能最好的。

    【讨论】:

    • ...感谢第二种可能的方法。我选择@fa06 只是因为他稍微快一点。你们两个都给了我我需要的东西并且它有效,现在我只需要选择哪个更适合我的特定用例;)
    • @Yoshi 。 . .如果我看到 fa06 的回答,我就不会回答了。
    【解决方案3】:

    这很容易完成。只需使用join子句即可。如下:

    select
        distinct b.user_id,a.move
    from
        table1 a
    join
        table2 b on a.id = b.movie_id and b.user_id in (1,3)
    

    【讨论】:

      【解决方案4】:

      使用 JOIN 从 2 个表中获取相关数据(基于 ID)并使用 WHERE 条件过滤结果

      SELECT secondTable.id, firstTable.movie
      FROM secondTable
      JOIN firstTable ON secondTable.movie_id = firstTable.id
      WHERE secondTable.user_id IN (1, 3)
      

      【讨论】:

        【解决方案5】:

        DISTINCT 语句用于只返回不同的值。

        你可以试试这个。我使用表名作为 Firsttable 和 Secondtable

        select DISTINCT f.id, f.movie from Firsttable f join Secondtable s on f.id = s.movie_id 
        where s.user_id in (1, 3)
        

        【讨论】:

          猜你喜欢
          • 2014-02-18
          • 2011-12-28
          • 2012-03-29
          • 2019-04-24
          • 1970-01-01
          • 2013-04-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多