Buscar una tabla MySQL usando los resultados de una consulta anterior

I can't think of an easy to phrase this question so I'll just put it out there: Is it possible to search a MySQL table using results from another query? (Using PHP for what it's worth)

What I'm trying to do is retrieve all of the scores for a user's contacts.

Por ejemplo:

SELECT user_2_id FROM contacts WHERE member_id = '1'

Now I'd like to retrieve all results from the table 'scores' where member_id matches any result from the above query (any 'user_2_id').

I just can't think of how to do it... but this is the data I'm trying to get to:

SELECT score_id FROM scores WHERE member_id = 'ANY RESULT FROM THE PREVIOUS QUERY'

I'd like to do this without using a WHILE loop in PHP because if a user happens to have 200 contacts (unlikely) it will be a lot of queries.

I'm sure there is a fairly simple way to do this but I just can't think of it. Help please!

preguntado el 01 de febrero de 12 a las 03:02

2 Respuestas

SELECT s.score_id FROM contacts c INNER JOIN scores s ON s.member_id = c.user_2_id WHERE c.member_id = 1

Respondido 01 Feb 12, 08:02

You can use subquery:

SELECT score_id FROM scores WHERE member_id IN (SELECT user_2_id FROM contacts WHERE member_id = '1')

Or you can use join:

SELECT s.score_id 
FROM scores s 
INNER JOIN contacts c 
ON s.member_id = c.user_2_id 
WHERE c.member_id = '1'

Respondido 01 Feb 12, 07:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.