-1

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?

  • Does this answer your question? [Use results from one sql query in another where statement (subquery?)](https://stackoverflow.com/questions/13779338/use-results-from-one-sql-query-in-another-where-statement-subquery) – philipxy Jun 19 '22 at 20:51

2 Answers2

0

Use exists:

SELECT somecol
FROM anothertable a
WHERE EXISTS (
  SELECT * FROM tablename t WHERE t.ID = a.parent
);
Stu
  • 30,392
  • 6
  • 14
  • 33
0

Just pass in your first query inside you second query:

SELECT 
`somecol` 
FROM 
`anothertable` 
WHERE 
`parent` 
IN (SELECT `id` FROM `tablename`)
Asgar
  • 1,920
  • 2
  • 8
  • 17