Reputation: 1281
I have these kinds of tables:
Customer1:
"Customer1" table:
--------------------------------
id | branch | company_id
--------------------------------
1 | typical | 1
2 | natural | 8
--------------------------------
Customer2
"Customer2" table:
-------------------------------
id | company | group_id
-------------------------------
1 | deux | 1
-------------------------------
Customer3
"Customer3" table:
-------------------------------
id | group
-------------------------------
1 | alpha
-------------------------------
Now, how can I have an output using sql command/statement base from the tables like this one :
----------------------------
group | company | branch
----------------------------
alpha | deux | typical
Upvotes: 0
Views: 78
Reputation: 166346
You could try something like
SELECT [group],
[company],
[branch]
FROm Customer1 c1 INNER JOIN
Customer2 c2 ON c1.company_id = c2.id INNER JOIN
Customer3 c3 ON c2.group_id = c3.id
To ensure that you always show all the values, you might want to take a look at using LEFT JOINS
Something like
SELECT [group],
[company],
[branch]
FROm Customer1 c1 LEFT JOIN
Customer2 c2 ON c1.company_id = c2.id LEFT JOIN
Customer3 c3 ON c2.group_id = c3.id
Here is a nice article that explains the difference between the various JOIN types
Introduction to JOINs – Basic of JOINs
Upvotes: 3
Reputation: 17126
This should be what you are looking for- However this may not be what you are looking for if tables have multiple records for same id
SELECT C3.group, C2.company, C1.branch
FROm Customer1 c1 INNER JOIN
Customer2 c2 ON c1.company_id = c2.id INNER JOIN
Customer3 c3 ON c2.group_id = c3.id
Upvotes: 1
Reputation: 1825
The example-values you gave us would not result in any matches if you run a join because the IDs don't match. However this is what the query would look like
select [group], company, branch
from Customer3 c3
join Customer2 c2 on c3.ID = c2.group_id
join Customer1 c1 on c2.id = c1.company_id
Upvotes: 0