Search code examples
sqlselectsubqueryinner-joinwhere-clause

Select a bunch of data given a list of key


I have just started learning SQL and I have encountered a problem. I am completely new to SQL, and I do not even know which keywords to google to tackle this problem.

I have two table:

  1. tablea
id | name
01 | abc
02 | ahb
03 | aen
04 | aev
05 | aca
06 | aee
07 | abc
08 | ahr

and a second one:

  1. tableb
group | name_id
A     |    01
A     |    02
A     |    03
A     |    04
A     |    05
A     |    06
B     |    07
B     |    08

Let's say I want to SELECT all the names belong to group A.

I wrote the following code:

SELECT name FROM tablea WHERE id = (SELECT name_id from tableb WHERE group = "A");

However, the result only give me a single line.


Solution

  • You have to use IN instead of =

    SELECT name FROM tablea WHERE id IN (SELECT name_id from tableb WHERE group = "A");