1

Can I do like this

select * 
from tableA JOIN 
tableB ON tableA.id=tableB.id 
where tableB.someId = select id from otherTable where anotherId = 1

I have 2 where, possible?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

3 Answers3

6

You can use = when the subquery returns only 1 value.

When subquery returns more than 1 value, you will have to use IN or EXISTS:

  1. Using IN:

    select * 
    from tableA JOIN 
    tableB ON tableA.id=tableB.id 
    where tableB.someId IN (select id 
                        from otherTable 
                        where anotherId = 1)
    

    IN determines whether a specified value matches any value in a subquery or a list.

    Read more here.

  2. USING EXISTS:

    select * 
    from tableA JOIN 
    tableB ON tableA.id = tableB.id 
    where EXISTS (select id 
          from otherTable 
          where anotherId = 1
          and tableB.someId = otherTable .id)
    
Raging Bull
  • 18,593
  • 13
  • 50
  • 55
  • You don't *have to use * `in`. In fact, `exists` can have better performance. `in` is a totally reasonable option though. – Gordon Linoff Apr 25 '14 at 13:57
1

You could use the IN Clause:

select * 
from tableA JOIN 
tableB ON tableA.id = tableB.id 
where tableB.someId IN (select id 
                        from otherTable
                        where anotherId = 1)

You could also use the EXISTS Condition:

select * 
from tableA JOIN 
tableB ON tableA.id = tableB.id 
where EXISTS (select id 
              from otherTable ot
              where anotherId = 1
              and tableB.someId = ot.id)

= would also work fine, if the subquery returned a single value.

Difference between EXISTS and IN

Community
  • 1
  • 1
John Bupit
  • 10,406
  • 8
  • 39
  • 75
0
select * 
from tableA 
JOIN tableB ON tableA.id=tableB.id 
join otherTable ON tableb.id = othertable.id 
where otherTable.anotherId = 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311