0

If I have a list of ID's that I have selected from a statement

SELECT id FROM myTable WHERE name = 'TEST'

This would return just the ids (1001, 1002, 1003, etc...) Then I want to perform another SELECT statement to retrieve all the titles for all those ids.

SELECT title FROM myTable2 WHERE id = XXXX

the id in table2 is the foreign key of table2. id in myTable is the Primary Key. How can I go about retrieving all the titles from those ids. I was thinking about storing all the results of the first select statement in an array, and then using a while loop to iterate through the list and return each result into another array, but my fear is that when the database gets big if it has to return 1000 rows that could be some bad overhead. So in PHP or SQL what is the best way to perform this?

3 Answers 3

4

You can use a subquery:

SELECT title
FROM myTable2
WHERE id IN (
 SELECT id 
  FROM myTable
  WHERE name = 'TEST'
)

Another way to do it would to be use a JOIN, to avoid the sub-query:

SELECT title
FROM myTable2 
LEFT JOIN myTable
 ON myTable.id = myTable2.id
WHERE myTable.name = 'TEST'
Sign up to request clarification or add additional context in comments.

4 Comments

INNER JOIN better fits the task
But a LEFT JOIN is generally more efficient than the INNER, and the WHERE condition on myTable.name prevents the return of any rows in myTable2 that don't exist in myTable anyway.
INNER JOIN is always more efficient than LEFT JOIN if everything else is the same
So still don't want to change the answer? ;-)
1

You should just be able to select them at the same time.

SELECT a.id, b.title 
  FROM myTable a, myTable2 b 
  WHERE a.name = 'TEST' AND b.id = a.id;

Comments

-1

to select both:

 SELECT id, title FROM mytable WHERE name="TEST"

or to select the whole row

SELECT *  FROM mytable WHERE name="TEST"

if its two tables you are selecting from:

SELECT id, title FROM mytable A JOIN mytable2 B USING (id)

5 Comments

(*) is not a valid sql syntax
And your last query probably will throw a error about ambiguously specified column name
it was in response to his example, he chose the column name.
@JimmyBanks he meant the column name id you use it twice and don't specify what table it is coming from. SQL will see that there are two possibilities and throw and error.
if the id specifies the row of both tables its not necessary to specify what table it is coming from, otherwise a JOIN AS rather than JOIN USING would be necessary. From what he wrote the tables arent auto-incrementing, but the ID is what specifies the rows are correlated together.

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.