Joining two tables in a select

前端 未结 2 1197
庸人自扰
庸人自扰 2021-01-25 21:16

I have two tables:

TABLE 1
ID   VALUE   
1    ABC
2    DEF
3    GHI
4    JKL
5    XYZ

TABLE 2
ID  T1_ID  VALUE 
1   1      A
2   1      B
3   2      A
4   3            


        
相关标签:
2条回答
  • 2021-01-25 21:48

    Tadaaah! Without a subquery.

    select distinct
      t1.*
    from
      Table1 t1
      inner join Table2 t2a on t2a.t1_ID = t1.ID and t2a.VALUE = 'A'
      inner join Table2 t2b on t2b.t1_ID = t1.ID and t2b.VALUE = 'B'
    
    0 讨论(0)
  • 2021-01-25 21:54
    SELECT t1.ID,
           t1.VALUE
    FROM   Table1 t1
           JOIN Table2 t2
             ON t1.ID = t2.T1_ID
    WHERE  t2.VALUE IN ( 'A', 'B' )
    GROUP  BY t1.ID,
              t1.VALUE
    HAVING COUNT(DISTINCT t2.VALUE) = 2
    
    0 讨论(0)
提交回复
热议问题