Home > other >  MySQL: Taking mulitple IDs returned from one query and passing the value in the "IN" of an
MySQL: Taking mulitple IDs returned from one query and passing the value in the "IN" of an

Time:06-20

So let's say that I have a query:

SELECT `id` FROM `tablename`

This will returns some IDs in rows. Now I want to use these IDs to get data from another table with the 'IN' function.

SELECT `somecol` FROM `anothertable` WHERE `parent` IN ( {IDs here} )

I could do this with PHP using 2 different queries. But I wanted to know how or can it be done with MySQL alone, using only one query?

CodePudding user response:

Use exists:

SELECT somecol
FROM anothertable a
WHERE EXISTS (
  SELECT * FROM tablename t WHERE t.ID = a.parent
);

CodePudding user response:

Just pass in your first query inside you second query:

SELECT 
`somecol` 
FROM 
`anothertable` 
WHERE 
`parent` 
IN (SELECT `id` FROM `tablename`)
  • Related