Sql join two tables

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 

Can someone show me how to write a query and get the result as above, thanks a lot! I tried to join, left and right to join. nothing happens.

+8
sql mysql tsql left-join
source share
5 answers

You can write a left outer join between the two tables. The best way to understand is to check the image below.

Request for your requirement

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

Reading this original article in Code Draft will help you a lot: Visual presentation of SQL joins .

alt text

Find the original in: Difference between JOIN and OUTER JOIN in MySQL .

+15
source share
 SELECT A.uid, A.name, B.address FROM A LEFT OUTER JOIN B ON A.uid = B.uid 
+2
source share

You say that you tried the left connection, but did not give any attempts - one of the first logical attempts:

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

Hey presto! it gives you what you were after.

+1
source share

You can use any connection. I am writing this request for a complete connection.

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

I assume that after an empty value, if for B there is no value that has the same uid in A.

If so, IFNULL will return the default value that you specified if the parameter is null (ISNULL is used in MSSQL):

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

This will result in something like:

 test1 address1 test2 address2 test3 test4 address3 
+1
source share

All Articles