Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two sql result

Tags:

sql

my first result looks like this

ID       Name
----------------------------------
1        George
2        Peter
3        San

my other result looks like this

AnotherID     ID     Note
-----------------------------------
1             1      georgesnote1
2             1      georgesnote2
3             3      sansnote1
4             1      georgesnote3

How I want them to look:

ID       Name        Note
----------------------------------
1        George      georgesnote1
1        George      georgesnote2
1        George      georgesnote3
2        Peter       NULL
3        San         sansnote1

My SQL knowledge pretty much limits me to achieve this. I guess I need something like UNION ALL. INNER JOIN OR LEFT OUTER JOIN doesnt work. My actual query is around 21 lines so this is not a beginner question. What I need is to join two results based on same IDs. Please someone guide me.

like image 699
Cute Bear Avatar asked Apr 18 '26 23:04

Cute Bear


1 Answers

You need a LEFT JOIN.

check out http://www.w3schools.com/sql/sql_join_left.asp

Assugming the first table is called first and the second is called second. The column id on the first table will be matched to the column id on the second table.

SELECT first.id, first.name, second.note
FROM first
LEFT JOIN second
ON first.id = second.id
ORDER BY first.id
like image 56
Baconator507 Avatar answered Apr 20 '26 15:04

Baconator507