2012-05-12 16 views
14

Vamos a llamar a esta tabla terms_relation:seleccionar filas con el ID de otra tabla

+---------+----------+-------------+------------+------------+--+ 
| term_id | taxonomy | description | created_at | updated_at | | 
+---------+----------+-------------+------------+------------+--+ 
|  1 | categ | non   | 3434343434 | 34343433 | | 
|  2 | categ | non   | 3434343434 | 3434343434 | | 
|  3 | tag  | non   | 3434343434 | 3434343434 | | 
|  4 | tag  | non   | 3434343434 | 3434343434 | | 
+---------+----------+-------------+------------+------------+--+ 

Y esta es la tabla terms:

+----+-------------+-------------+ 
| id | name  | slug  | 
+----+-------------+-------------+ 
| 1 | hello  | hello  | 
| 2 | how are you | how-are-you | 
| 3 | tutorial | tutorial | 
| 4 | the end  | the-end  | 
+----+-------------+-------------+ 

¿Cómo seleccionar todas las filas de la tabla terms y mesa terms_relation donde está taxonomía en la tabla terms_relation es categ? ¿Necesitaré dos consultas para esto o podría usar una declaración join?

+0

Aprender sobre [une SQL] (http://www.codinghorror.com/blog/2007/10/a-visual -explicación-de-sql-joins.html). – eggyal

+2

Sí, obtenga información sobre las combinaciones de SQL. Aprenda en http://sqlzoo.net/ y http://sqlfiddle.com/ –

Respuesta

39

Prueba este (sub consulta):

SELECT * FROM terms WHERE id IN 
    (SELECT term_id FROM terms_relation WHERE taxonomy = "categ") 

O usted puede intentar esto (UNIRSE):

SELECT t.* FROM terms AS t 
    INNER JOIN terms_relation AS tr 
    ON t.id = tr.term_id AND tr.taxonomy = "categ" 

Si desea recibir todos los campos de dos tablas:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
    FROM terms AS t 
    INNER JOIN terms_relation AS tr 
    ON t.id = tr.term_id AND tr.taxonomy = "categ" 
+0

Actualizó una respuesta. Es simple, solo agregue lo que necesita justo después de SELECCIONAR – gahcep

+1

increíble, ustedes dos están en lo cierto. Es difícil elegir, ¡gracias! – Michelle

+0

Corrígeme si me equivoco, pero creo que JOIN es un orden de magnitud más eficiente que el método de subconsulta. –

11

Se puede utilizar una subconsulta:

SELECT * 
FROM terms 
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ'); 

y si es necesario para mostrar todas las columnas de ambas tablas:

SELECT t.*, tr.* 
FROM terms t, terms_relation tr 
WHERE t.id = tr.term_id 
AND tr.taxonomy='categ' 
0
SELECT terms.* 
FROM terms JOIN terms_relation ON id=term_id 
WHERE taxonomy='categ' 
Cuestiones relacionadas