0

For some reason I have a hard time grasping joins and this one should be very simple with the knowledge that I have in SQL.

Anyway, I have 2 tables. We will call them TableA and TableB. One of the columns in TableA is "ID". TableB only consists of the column "ID". I want to return all rows in TableA whose ID is present in TableB.

I know this should be very simple to figure out, but my brain doesn't want to work today.

danglesauce19
  • 133
  • 1
  • 4
  • 14
  • I would use `EXISTS` or `IN`. – Gordon Linoff Apr 13 '16 at 18:56
  • Possible duplicate of [Select distinct ... inner join vs. select ... where id in (...)](http://stackoverflow.com/questions/2638989/select-distinct-inner-join-vs-select-where-id-in) – skmathur Apr 13 '16 at 19:19
  • Possible duplicate of [SQL JOIN and different types of JOINs](http://stackoverflow.com/questions/17946221/sql-join-and-different-types-of-joins) – Tab Alleman Apr 13 '16 at 19:29

3 Answers3

3

You can do this using an EXISTS:

Select  A.*
From    TableA  A
Where   Exists
(
    Select  *
    From    TableB  B
    Where   A.Id = B.Id
)

You can also use a JOIN if you wish, but depending on your data, you may want to couple that with a SELECT DISTINCT:

Select  Distinct A.*
From    TableA  A
Join    TableB  B   On  A.Id = B.Id

One thing to keep in mind is that the ID of TableA is not necessarily related to the ID of TableB.

Siyual
  • 16,415
  • 8
  • 44
  • 58
2

this should work

 SELECT B.ID 
 FROM TableA A 
 JOIN TableB B 
 ON (A.ID=B.ID)
 WHERE A.ID=B.ID
1

You can also use IN operator like this:

Select  *
From    TableA 
Where   ID in
(
    Select distinct ID
    From    TableB
)
irakliG.
  • 176
  • 10