4

I have a table with a list of IDs. I use a query to select that and then fetch it as an array (I know how to do this). Then I want to select rows from another table where the IDs are in the array fetched earlier.

How would I do this? Thanks in advance.

0

5 Answers 5

7

You'd most likely want to do a WHERE field IN (...) type query. It's essentially the equivalent of WHERE field=X or field=Y or field=Z or ... for every value listed in the IN clause.

Given that you've got an array of IDs already, the simplest way is to build the query like this:

$where_in = implode(',', $ids_array);

$query = "SELECT ... FROM yourtable WHERE idfield IN ($where_in);";

The usual provisos apply - be careful about SQL injection holes, always check query results for failure, etc...

Sign up to request clarification or add additional context in comments.

2 Comments

shouldn't this be $query = "SELECT ... FROM yourtable WHERE idfield IN (".$where_in.")"; ?
No. learn basic PHP syntax: php.net/manual/en/…
3

you can do this in one query

something like this SELECT table2.id FROM table2 WHERE table2.id IN (SELECT table1.id FROM table1 WHERE blablabla)

Comments

1
select value1,value2 from table2 where id in (1,2,3,4,5)

Comments

1

You could avoid doing this and consider JOIN tables. One query will fetch the matched records by IDs.

for an example

SELECT * FROM table1 t1 JOIN table2 t2 ON t1.ID=t2.ID

Comments

0

Suppose $values is the array, you can use the mysql IN keyword and php implode function to construct a query

$sql = "SELECT a, b FROM table WHERE id IN (" . implode(", ",$values) . ")";

implode will join the elements of the array using ", "

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.