2012-05-12 16 views
14

Chiamiamo questa tabella terms_relation:selezionando le righe con id da un altro tavolo

+---------+----------+-------------+------------+------------+--+ 
| 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 | | 
+---------+----------+-------------+------------+------------+--+ 

e questo è tavolo terms:

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

Come faccio a selezionare tutte le righe nella tabella terms e tavolo terms_relation dove è la tassonomia nella tabella terms_relation è categ? Avrò bisogno di due query per questo o potrei usare una dichiarazione join?

+0

Ulteriori informazioni [SQL unisce] (http://www.codinghorror.com/blog/2007/10/a-visual -explanation-di-sql-joins.html). – eggyal

+2

Sì, scopri i join SQL. Scopri http://sqlzoo.net/ e http://sqlfiddle.com/ –

risposta

39

Prova questo (subquery):

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

Or puoi provare questo (ISCRIVITI):

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

Se si desidera ricevere tutti i campi da due tabelle:

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

Aggiornamento di una risposta. È semplice, basta aggiungere ciò di cui hai bisogno subito dopo SELECT – gahcep

+1

incredibile, voi due ragazzi siete corretti. È difficile scegliere, grazie! – Michelle

+0

Correggetemi se sbaglio, ma penso che JOIN sia un ordine di grandezza più efficiente del metodo subquery. –

11

È possibile utilizzare una sottoquery:

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

e se avete bisogno di mostrare tutte le colonne di entrambe le tabelle:

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' 
Problemi correlati