2012-02-07 20 views
8
TABLE A >> 
uid name 
1 test1 
2 test2 
3 test3 
4 test4 

TABLE B >> 
uid address 
1 address1 
2 address2 
4 address3 

RESULT 
1 test1 address1 
2 test2 address2 
3 test3 
4 test4 address3 

Qualcuno può mostrarmi come scrivere una query e recuperare il risultato come sopra, Grazie mille! ho provato a partecipare, a sinistra ea destra join. tutto non produce nulla.sql join two table

+0

W cappello hai provato con i tuoi join? Cedo i tentativi? –

risposta

15

è possibile scrivere sinistra outer join tra questa due tabelle Il modo migliore per capire è controllare l'immagine qui sotto

Query per il vostro requisito

SELECT A.uid, A.name, B.address FROM A LEFT JOIN B ON A.uid=B.uid 

La lettura di questo articolo originale sul Il progetto Codice aiuterà molto: Visual Representation of SQL Joins.

alt text

Trova un originale alla: Difference between JOIN and OUTER JOIN in MySQL.

+0

Questi sono i diagrammi delle operazioni impostate, non i join ad es. quello in basso a sinistra è 'A UNION B', quello nel mezzo è' A INTERSECT B', ecc. – onedaywhen

+0

mi piace il tuo diagramma, spiega tutto così bene. Grazie mille mcuh – Bruce

1

Tu dici si è tentato a sinistra unirsi ma non ha dato alcun tentativo --- uno dei primi tentativi di logica sarebbe stata:

SELECT A.uid, A.name, B.address 
FROM A 
LEFT JOIN B ON A.uid=B.uid 

Hey Presto! ti dà quello che cercavi.

2
SELECT A.uid, A.name, B.address FROM A LEFT OUTER JOIN B ON A.uid = B.uid 
1

È possibile utilizzare qualsiasi join.Io scrivo questa query per l'unione completa.

select A.uid,A.name,B.address from A FULL JOIN B ON A.uid = B.uid 
1

immagino che stai dopo un valore vuoto se non v'è alcun valore per B, che sta avendo lo stesso UID in A.

Se questo è il caso, IFNULL restituirà il valore predefinito specificato nel caso il parametro è nullo (ISNULL è utilizzato in MSSQL):

SELECT A.value, IFNULL(B.value, '') 
FROM A LEFT JOIN B 
ON A.uid = B.uid 

Ciò produrrà qualcosa come:

test1 address1 
test2 address2 
test3 
test4 address3