SQL efficient way to join a table where all values exist

前端 未结 3 1195
说谎
说谎 2020-12-12 01:45
table 1
item    group_id
123     aaaa
432     bbbb
534     aaaa
765     cccc
656     aaaa
656     cccc
111     cccc

group_id    group_name
aaaa        groupA
bbbb           


        
相关标签:
3条回答
  • 2020-12-12 02:15

    You can use the INTERSECT operator. INTERSECT returns the shared distinct values from both tables. In practice I've found this faster than other methods.

    In this example I put intersect in-between the queries below:

    SELECT T2.groupName 
      FROM table1 T1 INNER JOIN table2 T2 ON T1.groupID = T2.groupID
     WHERE T1.itemID = 765
    
    INTERSECT 
    
    SELECT T2.groupName 
      FROM table1 T1 INNER JOIN table2 T2 ON T1.groupID = T2.groupID
     WHERE T1.itemID = 656
    

    Provides output:

    groupName
    ---------
    groupC
    
    0 讨论(0)
  • 2020-12-12 02:22

    The simplest thing would be to use group by and having:

    SELECT group_name
    FROM table2 g
    JOIN table1 t on g.group_id = t.group_id
    WHERE t.item in (765,656)
    GROUP BY group_name
    HAVING COUNT(DISTINCT t.item) = 2
    
    0 讨论(0)
  • 2020-12-12 02:26
    SELECT DISTINCT t1.group_name 
                        FROM table1 t1 join table1 t2 join groups g
                            ON t1.group_id = t2.group_id 
                               and t1.item = 765 
                               and t2.item = 656
                               and g.group_id = t1.group_id
    
    0 讨论(0)
提交回复
热议问题